找出是否有互联网,包括wifi或数据(Swift 3) [英] Figure out if there is internet or not, including wifi or data (Swift 3)

查看:93
本文介绍了找出是否有互联网,包括wifi或数据(Swift 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了可达性代码,很遗憾,它仅适用于wifi网络.我需要一个代码来确定一个人是否可以连接互联网:这包括wifi和数据.任何帮助,我们将不胜感激!

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!

推荐答案

您可以使用可达性框架.通过CocoaPodspod 'ReachabilitySwift', '~> 3'安装.

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

要使用它:
声明一个全局变量:

To use it:
Declare a global variable:

var reachability = Reachability()!

添加观察者并在viewWillAppear中启动通知程序:

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
        }
    }
}

这篇关于找出是否有互联网,包括wifi或数据(Swift 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆