[英]NotificationCenter addObserver for reachabilityChanged not working
在這里,我想添加觀察者來檢查我是否有互聯網連接,
我使用了https://github.com/ashleymills/Reachability.swift的可達性-swift 5.0,我使用了這個代碼
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let reachability = try! Reachability()
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability?.startNotifier()
print("start notifierrrr")
}catch{
print("could not start reachability notifier")
}
...
}
當我打開/關閉我的無線網絡時,function 根本沒有調用
@objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.currentReachabilityStatus {
case .reachableViaWiFi:
print("Reachable via WiFi bbb")
case .reachableViaWWAN:
print("Reachable via WWAN bbb")
case .notReachable:
print("Network not reachable bbb")
}
}
注意:我正在使用真實設備 iphone 7 並使用 ReachabilitySwift (5.0.0)
public convenience init(hostname: String,
queueQoS: DispatchQoS = .default,
targetQueue: DispatchQueue? = nil,
notificationQueue: DispatchQueue? = .main) throws {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else {
throw ReachabilityError.failedToCreateWithHostname(hostname, SCError())
}
在start notifier()
之前使用主機名( www.google.com
)初始化可達性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.