iOS 监听网络状态变化有多种方式,iOS 12 之后系统提供了 Network 框架,可以更加方便地监听网络状态变化。
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
DispatchQueue.main.async {
switch path.status {
case .satisfied: // 已连接
break
case .unsatisfied:
break
case .requiresConnection:
break
}
}
}
let queue = DispatchQueue(label: "Monitor")
monitor.start(queue: queue)
调用 start 之后,网络状态变化就会调用 pathUpdateHandler。第一次调用后也会立即触发回调。
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
final public class NWPathMonitor {
...
}
可以看到,NWPathMonitor 需要 iOS 12.0 以上才能调用。
- status
public enum Status : Sendable {
/// The path has a usable route upon which to send and receive data
case satisfied
/// The path does not have a usable route. This may be due to a network interface being down, or due to system policy.
case unsatisfied
/// The path does not currently have a usable route, but a connection attempt will trigger network attachment.
case requiresConnection
}
satisfied 表示可以发送和接收数据;unsatisfied 表示不可用,可能由于网络故障或系统策略等;requiresConnection 表示当前不可用,但是会触发网络连接,一般是第一次启动的时候。
- 监听某一种网络
如果想要监听具体某一种网络,可以在初始化时指定。
let monitor = NWPathMonitor(requiredInterfaceType: .wifi)
可以指定的类型如下:
public enum InterfaceType : Sendable {
/// A virtual or otherwise unknown interface type
case other
/// A Wi-Fi link
case wifi
/// A Cellular link
case cellular
/// A Wired Ethernet link
case wiredEthernet
/// The Loopback Interface
case loopback
}
- 取消监听
如果想要取消监听,可以调用 cancel 方法。
monitor.cancel()
网友评论