简介
NWPathMonitor 是 Network 框架中的一个类,用于观察网络状态并监控网络接口。 它在 iOS 12 及以上版本可用。
import Network
要接收回调,必须持有 NWPathMonitor 实例。
class NetworkMonitorViewController: ViewController {
let monitor = NWPathMonitor()
}
通过 requiredInterface 可以只观察特定的网络接口。
let wifiMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
NWPathMonitor 支持的接口列表见这里。
https://developer.apple.com/documentation/network/nwinterface/interfacetype
检测网络变化
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
// Connected
}
}
开始监听
创建一个后台队列,并把它传给 start()。
let queue = DispatchQueue.global(qos: .background)
monitor.start(queue: queue)
就这么简单,是不是很方便?
顺便说一句,NWPath 是什么?
NWPath 包含了可用接口、当前是 IPv6 还是 IPv4 等信息。
可以通过 currentPath 获取它。
monitor.currentPath
总结
本文介绍了 NWPathMonitor,展示了如何用这么简洁的代码来检测网络变化。
NWPathMonitor
- 在 iOS 12 中即可使用
- 使用简单
- 完全可以用来替代 Reachability