Figure out if there is internet or not, including

2020-05-03 09:37发布

I found a reachibility code online, unfortunately it only works for the wifi Network. I Need a code to determine if a person has an internet connection: this includes wifi and data. Any help is greatly appreciated!

1条回答
Root(大扎)
2楼-- · 2020-05-03 10:29

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
        }
    }
}
查看更多
登录 后发表回答