Have a look at the Network
framework. It is super powerful and flexible and allows direct access to protocols like TLS, TCP, and UDP for your custom application protocols. It is Swift-ready and easy to use.
import Network
let connection = NWConnection(host: "www.google.com", port: .https, using: .tcp)
connection.stateUpdateHandler = { (newState) in
switch(newState) {
case .ready:
print("Handle connection established")
case .waiting(let error):
print("Waiting for network", error.localizedDescription)
case .failed(let error):
print("Fatal connection error", error.localizedDescription)
default:
break
}
}
connection.start(queue: .main) // Use some other queue if doing it for real.
The code above will work even in Playground (and fire the stateUpdateHandler
at least once). In real app stateUpdateHandler
will be called every time the state changes.
BTW, URLSession
, is built upon this framework.