Figure out if there is internet or not, including wifi or data (Swift 3) [closed]

半腔热情 提交于 2019-12-02 08:28:47

You can use the Reachability framework. Install it through CocoaPods with pod 'ReachabilitySwift', '~> 3'.

To use it:
Declare a global variable:

var reachability = Reachability()!

Add an observer and start the notifier in your viewWillAppear:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: ReachabilityChangedNotification,object: reachability)
    do{
        try reachability.startNotifier()
    }catch{
        print("could not start reachability notifier")
    }
}

Add a function to detect changes in the network:

func reachabilityChanged(note: NSNotification) {
    reachability = note.object as! Reachability
    if !reachability.isReachable {
        // Network not reachable
    }
    else{
        if reachability.isReachableViaWiFi {
            // Reachable via WiFi
        } else {
            // Reachable via Cellular
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!