NWConnection connection.stateUpdateHandler .cancelled state doesn't fire

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:

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.

Replies

It turns out this seems to be an issue with the simulator. I've been playing around and searching the internet for 12 hrs and nothing. I finally tried it out on my real device and 2 simulators. I sent the real device to the background and the connection.stateUpdateHandler's .failed and .cancelled worked fine on the simulators.

On the reverse when I sent either of the simulators to the background the real device's connection.stateUpdateHandler didn't get hit.

I don't have another real device on hand to try to see what happens with 2 real devices. This is a strange issue.

Any ideas out there?