My Reachability Notifier is only able to be called once

眉间皱痕 提交于 2019-12-01 12:44:26
Rajan Maheshwari

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!