Search code examples
network-framework

Handling NWConnection timeout


How to handle a connection timing out?

let connection = NWConnection(to: endpoint, using: .tcp)
connection.stateUpdateHandler = { [self] newState in
    print("newState: \(newState)")
}
connection.start(queue: .main)

Log:

newState: preparing
nw_socket_handle_socket_event [C1.1.4.1:1] Socket SO_ERROR [60: Operation timed out]
... several more times

The stateUpdateHandler function is never called again.


Solution

  • It turns out NWConnection doesn't implement timeouts. We have to do it ourselves:

    let connectionTimeout = 15
    connection.start(queue: .main)
    
    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(connectionTimeout)) { [weak self] in
            guard let self = self else { return }
            if self.connection.state != .ready {
                self.connection.stateUpdateHandler?(.failed(.posix(.ETIMEDOUT)))
            }
        }