看看Network
框架。它超级强大且灵活,允许直接访问 TLS、TCP 和 UDP 等协议,用于您的自定义应用程序协议。它是 Swift 就绪且易于使用的。
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))