My Reachability Notifier is only able to be called once

前端 未结 2 436
天命终不由人
天命终不由人 2021-01-16 03:19

So, I have the following in my AppDelegate.
It will notify my when I turn my WIFI off but will not react after that initial run.
I have had this working in the past.

相关标签:
2条回答
  • 2021-01-16 03:47

    Try passing nil for the object parameter in addObserver. Also, for Swift 3, I had to initialize it with self.reachability = Reachability.forInternetConnection()

    0 讨论(0)
  • 2021-01-16 04:09

    There are some changes in Reachability in Swift 3. Download the latest Reachability.swift file and add that in your project. Link

    For Swift 2.x code please check my answer here

    Swift 3.x code

    Now in your AppDelegate take a Reachability class object

    private var reachability:Reachability!
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
    
        //Network Reachability Notification check
        NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged), name: ReachabilityChangedNotification, object: nil)
    
        self.reachability = Reachability.init()
        do {
            try self.reachability.startNotifier()
        } catch {
        }
        return true
    }
    

    reachabilityChanged method defination

    //MARK:- Network Check
    func reachabilityChanged(notification:Notification) {
        let reachability = notification.object as! Reachability
        if reachability.isReachable {
            if reachability.isReachableViaWiFi {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
        } else {
             print("Network not reachable")
        }
    }
    

    This will be always called whenever user switches from Wifi to Cellular and vice versa or when Network Connects and Disconnects and vice versa.
    Working fine in my case.

    Read the documentation for more details in Swift 3 breaking changes section

    Made a sample for you

    https://www.dropbox.com/sh/bph33b12tyc7fpd/AAD2pGbgW3UnqgQoe7MGPpKPa?dl=0

    0 讨论(0)
提交回复
热议问题