sat*_*ker 7 networking objective-c ios
在我的应用程序中,每当发生网络更改时,例如当应用程序连接或断开连接或更改(wifi 到数据)网络时,我都必须发出警报。
但是通过访问 url 找到它似乎很昂贵。
iOS 中是否有任何公共 API 可以执行此操作。
我跟着这个教程
https://www.youtube.com/watch?v=wDZmz9IsB-8
信用 --> 瓦西尔·努涅夫
下载这个类并导入到我的项目 --> Reachability.swift
https://github.com/ashleymills/Reachability.swift
(Reachability.swift) --> 解压 -->Sources/Reachability.swift
这是我的视图控制器
import UIKit
class ViewController: UIViewController {
let reachability = Reachability()!
override func viewDidLoad() {
super.viewDidLoad()
reachability.whenReachable = { _ in
DispatchQueue.main.async {
self.view.backgroundColor = UIColor.green
}
}
reachability.whenUnreachable = { _ in
DispatchQueue.main.async {
self.view.backgroundColor = UIColor.red
}
}
NotificationCenter.default.addObserver(self, selector: #selector(internetChanged), name: Notification.Name.reachabilityChanged , object: reachability)
do{
try reachability.startNotifier()
} catch {
print("Could not strat notifier")
}
}
@objc func internetChanged(note:Notification) {
let reachability = note.object as! Reachability
if reachability.isReachable{
if reachability.isReachableViaWiFi{
self.view.backgroundColor = UIColor.green
}
else{
DispatchQueue.main.async {
self.view.backgroundColor = UIColor.orange
}
}
} else{
DispatchQueue.main.async {
self.view.backgroundColor = UIColor.red
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11075 次 |
| 最近记录: |