NWConnection Timeout

I am using Apples Network framework to build a TCP connection to a server. It locks like this:

Code Block let testConnection = NWConnection(host: NWEndpoint.Host(server!.serverAddress), port: NWEndpoint.Port(server!.serverPort)!, using: .tcp)
testConnection.stateUpdateHandler = ({ state in
print("TCP state change to: \(state)")
switch state {
case .setup:
break
case .waiting(let error):
print("Waiting Error \(error)")
testConnection.cancel()
break
case .preparing:
break
case .ready:
beginCommunication()
break
case .failed(let error):
print("\(error)")
break
case .cancelled:
break
default:
break
}
})

The serverAddress and serverPort is entered by the user. I want to test the connection. Now my problem is, that if the user is entering an invalid address / port combination (the service is not offered by the server). I stuck in the preparing state for quite a long time. After that I get to the waiting stage (with error message POSIXErrorCode: Operation timed out).
Is there any way to set the timeout for this first connection process ?
Thanks for your ideas
Answered by DTS Engineer in 637497022
The NWConnection API is inherently asynchronous. If you want a custom timeout, just use a timer.

Having said that, I’m going to caution you against setting the timeout too low. There’s nothing more annoying that seeing a connection time out just as it was about to complete. The default timeouts are long (generally in the 30 to 75 second range) for a reason.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"

Is there any way to set the timeout for this first connection process ?

I'm just watching the documentations and not tested, but NWProtocolTCP.Options has a parameter named connectionTimeout.

Can't you use it?
Thanks OOPer,

this I had tried, but it seem that this is a timeout for the established TCP-connection, but I am one layer above in which the server is not answering because the port is wrong....

Accepted Answer
The NWConnection API is inherently asynchronous. If you want a custom timeout, just use a timer.

Having said that, I’m going to caution you against setting the timeout too low. There’s nothing more annoying that seeing a connection time out just as it was about to complete. The default timeouts are long (generally in the 30 to 75 second range) for a reason.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
Thanks, eskimo!
I have tied the timer which works.

But since in the application this problem only appears in a kind of connection test process I decided to start the connection and show an ALERT with CANCEL button. The ALERT will be closed on reaching .cancelled state. Connection is cancelled on state .ready, .waiting and .failure as well as when CANCEL is pressed. The I inform the main thread about the result by a Notification:

Code Block func showTestingAlert () {
        if alert == nil {
            alert = UIAlertController(title: "Test connection", message: "Please wait...", preferredStyle: .alert)
 
            if let alert = alert {
                alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
                    self.testConnection.forceCancel()
                    NotificationCenter.default.post(name: Notification.Name("connectionTest"), object: "Canceled by user!")
                    self.alert = nil
                    return
                }))
                let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
                loadingIndicator.hidesWhenStopped = true
                loadingIndicator.style = UIActivityIndicatorView.Style.medium
                loadingIndicator.startAnimating()
                alert.view.addSubview(loadingIndicator)
                present(alert, animated: false, completion: nil)
}
        }
    }




You can indeed use NWProtocolTCP.Options to set a connection timeout like this:

Code Block
let options = NWProtocolTCP.Options()
options.connectionTimeout = 2
let params = NWParameters(tls: nil, tcp: options)
let connection = NWConnection(host: anyHost, port: anyPort, using: params)

So, no timer is needed.
NWConnection Timeout
 
 
Q