繁体   English   中英

NotificationCenter addObserver forreachabilityChanged 不起作用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM