- 使用Alamofire自带的NetworkReachabilityManager很方便。
import Alamofire
struct Network {
let manager = Alamofire.NetworkReachabilityManager()
func state() {
manager?.startListening { status in
switch status {
case .notReachable:
print("not reachable")
case .reachable(.cellular):
print("cellular")
case .reachable(.ethernetOrWiFi):
print("ethernetOrWiFi")
default:
print("unknown")
}
}
}
}
- 使用 Reachability.swift这个库也是不错的
let reachability = try! Reachability()
func netstate() {
reachability.whenReachable = { reachability in
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
reachability.whenUnreachable = { _ in
print("Not reachable") }
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}