;-)
Something about Network.framework I do not understand though:
I am using Network.framework via tcp to connect to a device which exposes a wifi network. Since I want to play nice I accept that the app disconnects the network when it is backgrounded and implemented a reconnect. So when my app gets back from background and gets active I create a new nwnetworkconnection. All works great. Except...
The problem I am facing is that sometimes my connection remains in .waiting and I don't know why.
I rely on a Wifi connection in the background. if the Wifi connection got lost during background, too, I try to establish the Wifi connection with NENetworkConnectionManager:
NEHotspotConfigurationManager.shared.apply(config, completionHandler: closure )
In the closure I reconnect my nwnetwork connection by establishing a new connection:
self.connection = connection
nwconnection = NWConnection(host: NWEndpoint.Host(addr), port: NWEndpoint.Port(integerLiteral: NWEndpoint.Port.IntegerLiteralType(CapPort)), using: .tcp)
nwconnection.stateUpdateHandler = { [weak self](newState) in
guard let self = self else { return }
guard let connection = self.connection else { return }
switch (newState) {
case .ready:
print_debug("NWHandler: Connection Ready!", level:10)
connection.capConnectionState = CAPConnectionState.expectingWelcome
self.readHeader()
case .waiting(_):
print_debug("NWHandler: Connection Waiting!", level:10)
connection.capConnectionState = CAPConnectionState.waiting
case .failed(_):
print_debug("NWHandler: Connection Failed!", level:10)
connection.capConnectionState = CAPConnectionState.networkError
default:
break
}
}
//Start the connection
nwconnection.start(queue: nwqueue)
What happens sometimes is that the connection remains in the .waiting stage and never connects or fails. I suspect this has to do with the Wifi network not being completly established (even though I am calling it in the completion of NEHotspotConfigurationManager.shared.apply.
I assumed that connectivity issues are supposed to be taken care of by Network.framework and that eventually when the host is reachable the connection would progress to connected or at least fail (so I could try again)? Problem is that on a higher level I cannot really deal with .waiting very well...
Everything works fine if Wifi is preconnected and I have a properly set-up network.
Do I expect the wrong thing and I need to test for reachability of the host before I start the connection? Or are there DispatchQueue issues? (i specify my network queue to handle the connection).
I am a bit lost with this one.
Thanks for your help!
Michael
EDIT: Seems like the reachability logic of Network.framework is linked to DNS is some way? I previously used the std. IP Address of the device and got stuck. Now I have Bonjour working and it works.