互联网连接状态 swift 可达性
Internet connection status swift reachability
我有以下代码来确定是否有互联网连接。此代码工作正常。我怎么知道我是否突然失去联系
var reachability:Reachability?
reachability = Reachability()
self.reachability = Reachability.init()
if((self.reachability!.connection) != .none)
{
print("Internet available")
}
可达性 class 是否具有报告连接断开的功能。如果无法通过可达性来处理该问题,那么其他选择是什么
在 AppDelegate 中声明这个 / Vc
let reachability = Reachability()!
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
//
当状态改变时调用这个方法
@objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .none:
print("Network not reachable")
}
}
//
为避免崩溃,请不要忘记取消注册
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
对于 iOS12+,我会使用 NWPathMonitor,这使得监控网络变化超级容易:
import Network
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
if path.status != .satisfied {
// Lost connection, do your thing here
}
}
monitor.start(queue: DispatchQueue(label: "network_monitor"))
当您完成监控时:
monitor.cancel()
我有以下代码来确定是否有互联网连接。此代码工作正常。我怎么知道我是否突然失去联系
var reachability:Reachability?
reachability = Reachability()
self.reachability = Reachability.init()
if((self.reachability!.connection) != .none)
{
print("Internet available")
}
可达性 class 是否具有报告连接断开的功能。如果无法通过可达性来处理该问题,那么其他选择是什么
在 AppDelegate 中声明这个 / Vc
let reachability = Reachability()!
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
//
当状态改变时调用这个方法
@objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .none:
print("Network not reachable")
}
}
//
为避免崩溃,请不要忘记取消注册
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
对于 iOS12+,我会使用 NWPathMonitor,这使得监控网络变化超级容易:
import Network
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
if path.status != .satisfied {
// Lost connection, do your thing here
}
}
monitor.start(queue: DispatchQueue(label: "network_monitor"))
当您完成监控时:
monitor.cancel()