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

推荐订阅源

F
Fortinet All Blogs
Microsoft Security Blog
Microsoft Security Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
C
Check Point Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
The Hacker News
The Hacker News
L
LINUX DO - 热门话题
T
Tenable Blog
Hugging Face - Blog
Hugging Face - Blog
Google Online Security Blog
Google Online Security Blog
博客园 - Franky
P
Proofpoint News Feed
H
Hacker News: Front Page
P
Privacy & Cybersecurity Law Blog
月光博客
月光博客
P
Proofpoint News Feed
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
博客园_首页
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
I
InfoQ
Stack Overflow Blog
Stack Overflow Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
博客园 - 叶小钗
T
Threat Research - Cisco Blogs
aimingoo的专栏
aimingoo的专栏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
MongoDB | Blog
MongoDB | Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hacker News - Newest:
Hacker News - Newest: "LLM"
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
O
OpenAI News
G
Google Developers Blog
Martin Fowler
Martin Fowler
罗磊的独立博客
S
SegmentFault 最新的问题
T
Tor Project blog
量子位

博客园 - 幻化成疯

今天又是一年的最后一个工作日 今天是最后一个工作日 过年了,龙年 新年又来了!今天是放假的最后前的最后一个工作日! 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)