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
// To try a connection to a host
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: .global(qos: .background))
// 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.
// To get general connection status:
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
if path.status != .satisfied {
print("Not connected")
}
else if path.usesInterfaceType(.cellular) {
print("Cellular 3/4/5g connection")
}
else if path.usesInterfaceType(.wifi) {
print("Wi-Fi connection")
print(path.status)
}
else if path.usesInterfaceType(.wiredEthernet) {
print("Ethernet connection")
}
}
monitor.start(queue: .global(qos: .background))