I have the same exact problem as this question.
device-1 browses, discovers, and sends a message to device-2. The connection is made. I hold a copy to the outgoing connection inside an array.
device-2 receives the message and I hold a copy of the incoming connection inside an array.
The same thing happens in reverse with device-2 to device-1 (peer-to-peer) setup.
When either device goes to the background, I iterate through the array, .cancel the connection, then remove it from the array. The problem is when the connection is no longer connected, the opposite device fires browser.browseResultsChangedHandler but it never fires connection.stateUpdateHandler, it will only fire if it itself shuts the connection down.
device-1:
device-1 is no longer connected, device-2 -only the browseResultsChangedHandler fires
The odd thing is if device-2 goes to the background (same step as device-1), then connection.stateUpdateHandler does fire.
Just to be clear when sending messages everything works fine on both devices and in both the browser and listener handlers.
device-1 browses, discovers, and sends a message to device-2. The connection is made. I hold a copy to the outgoing connection inside an array.
device-2 receives the message and I hold a copy of the incoming connection inside an array.
The same thing happens in reverse with device-2 to device-1 (peer-to-peer) setup.
When either device goes to the background, I iterate through the array, .cancel the connection, then remove it from the array. The problem is when the connection is no longer connected, the opposite device fires browser.browseResultsChangedHandler but it never fires connection.stateUpdateHandler, it will only fire if it itself shuts the connection down.
device-1:
Code Block var connections = [NWConnection]() @objc func backgroundNotification() { connections.forEach({ $0.cancel() }) connections.removeAll() // I've also tried cancelling and setting both the browser and listener to nil }
device-1 is no longer connected, device-2 -only the browseResultsChangedHandler fires
Code Block browser.browseResultsChangedHandler = { [weak self](results, changes) in for change in changes { switch change { // ... case .removed(let browseResult): if case .service(let name, let type, let domain, _) = browseResult.endpoint { // * only this runs * } default:break } } } var connections = [NWConnection]() connection.stateUpdateHandler = { [weak self](nwConnectionState) in // *.cancelled* and *.failed* never run switch nwConnectionState { // ... case .cancelled: connection.cancel() // ... loop the array and remove the connection case .failed(let error): connection.cancel() // ... loop the array and remove the connection default:break } }
The odd thing is if device-2 goes to the background (same step as device-1), then connection.stateUpdateHandler does fire.
Just to be clear when sending messages everything works fine on both devices and in both the browser and listener handlers.