简体   繁体   中英

NotificationCenter addObserver for reachabilityChanged not working

Here, i would like to addObserver to check if i got internet connection,

i used reachability-swift 5.0 from https://github.com/ashleymills/Reachability.swift and i use this code

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")
    }
    ...    
}

When i turn on/off my wi-fi, the function didn't called at all

@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")
  }
}

nb: i'm using real device iphone 7 and using 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())
        }

Intialise the reachability with a host name( www.google.com ) before start notifier()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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