From a55479c8ac15c4d2289035b2782963f2521049a1 Mon Sep 17 00:00:00 2001 From: ajinumoto Date: Thu, 20 Jul 2023 15:45:02 +0700 Subject: [PATCH] Update NWWebSocket.swift Fix multiple NWConnection during migrateConnection --- Sources/NWWebSocket/Model/Client/NWWebSocket.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/NWWebSocket/Model/Client/NWWebSocket.swift b/Sources/NWWebSocket/Model/Client/NWWebSocket.swift index 0ca9054..e02bf6b 100644 --- a/Sources/NWWebSocket/Model/Client/NWWebSocket.swift +++ b/Sources/NWWebSocket/Model/Client/NWWebSocket.swift @@ -23,6 +23,7 @@ open class NWWebSocket: WebSocketConnection { // MARK: - Private properties private var connection: NWConnection? + private var migratedConnection: NWConnection? private let endpoint: NWEndpoint private let parameters: NWParameters private let connectionQueue: DispatchQueue @@ -244,7 +245,9 @@ open class NWWebSocket: WebSocketConnection { /// or a `NWError` if the migration failed for some reason. private func migrateConnection(completionHandler: @escaping (Result) -> Void) { - let migratedConnection = NWConnection(to: endpoint, using: parameters) + migratedConnection?.cancel() + migratedConnection = nil + migratedConnection = NWConnection(to: endpoint, using: parameters) migratedConnection.stateUpdateHandler = { [weak self] state in guard let self = self else { return @@ -252,6 +255,7 @@ open class NWWebSocket: WebSocketConnection { switch state { case .ready: + self.connection?.cancel() self.connection = nil migratedConnection.stateUpdateHandler = self.stateDidChange(to:) migratedConnection.betterPathUpdateHandler = self.betterPath(isAvailable:)