惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
InfoQ
C
CERT Recently Published Vulnerability Notes
The Last Watchdog
The Last Watchdog
P
Proofpoint News Feed
D
Darknet – Hacking Tools, Hacker News & Cyber Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
T
Tenable Blog
博客园 - 三生石上(FineUI控件)
P
Privacy & Cybersecurity Law Blog
Simon Willison's Weblog
Simon Willison's Weblog
Jina AI
Jina AI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
博客园_首页
F
Fortinet All Blogs
博客园 - Franky
Latest news
Latest news
Last Week in AI
Last Week in AI
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hugging Face - Blog
Hugging Face - Blog
D
Docker
Project Zero
Project Zero
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
D
DataBreaches.Net
Google DeepMind News
Google DeepMind News
Cisco Talos Blog
Cisco Talos Blog
Y
Y Combinator Blog
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
H
Help Net Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Schneier on Security
C
Cybersecurity and Infrastructure Security Agency CISA
P
Proofpoint News Feed
PCI Perspectives
PCI Perspectives
Cloudbric
Cloudbric
V
Visual Studio Blog
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理

博客园 - 幻化成疯

今天又是一年的最后一个工作日 今天是最后一个工作日 过年了,龙年 新年又来了!今天是放假的最后前的最后一个工作日! Vue开发时运行npm install命令导致npm包自动升级而引起bug iOS AppIcon透明圆角导致的动画问题 iOS14 毛皮玻璃Blur效果英文教程推荐 iOS14 SceneKit Camera 的视角 Swift5 的 Enum iOS14 Core Location后台定位 用.Net 开发Windows Service ,合并dll到exe中 iOS SpriteKit 字体设置无效问题 2021又来到了! Dart 和 Javascript 中的await 和 async的理解 又离职了~ 留个纪念,过了这么多年,又干回Android了! mac上运行shell脚本遇到回车字符错误 - 幻化成疯 - 博客园 iOS12 中的后台下载与上传 以iphone作为热点时ios程序中的UDP广播地址
iOS12 判断网络链接状态NWPathMonitor
幻化成疯 · 2020-09-02 · via 博客园 - 幻化成疯

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)