iOS12 判断网络链接状态NWPathMonitor

iOS12 以前,如果想判断网络状态,我们需要引入一段苹果官方提供的代码,类名叫做Reachability。这么普通的功能竟然不是库自带的。好在苹果在iOS12 推出了 NWPathMonitor,能更加方便细致地监控网络状态了。

在网上看到了一篇好文章,
https://learnappmaking.com/nwpathmonitor-internet-connectivity/

我对其进行了翻译和总结

首先,需要引入 Network 库,
之后声明一个实例
let monitor = NWPathMonitor()

上面这段代码表示监听所有网络类型的状态,如果需要针对某一种网络,可以使用
let monitor = NWPathMonitor(requiredInterfaceType: .wifi)

其实主要使用的就2种,.wifi 和 .cellular

之后就可以使用以下代码判断当前网络状态:

 if monitor.currentPath.status == .satisfied {
     //网络可达
 }

还可以判断出是否正在使用某种网络
monitor.currentPath.usesInterfaceType(.wifi)

如果需要实时监听网络状态,还需要使用以下代码,并且要注意monitor的生命周期,不要被提前释放了。

monitor.pathUpdateHandler = { path in

    if path.status == .satisfied {
        print("Yay! We have internet!")
    }
}
let queue = DispatchQueue.global(qos: .background)
monitor.start(queue: queue)
原文地址:https://www.cnblogs.com/breezemist/p/13602730.html