如何通过可到达性在运行时检查网络连接更改以获取Internet连接?

时间:2019-03-08 11:44:43

标签: swift reachability

我正在使用this lib来检查可及性

下面是我的示例代码:

override func viewWillAppear(_ animated: Bool) {
    let reachability = Reachability()!
    NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
    do{
        try reachability.startNotifier()
    }catch{
        print("could not start reachability notifier")
    }
    getUserDetail()
}
@objc func reachabilityChanged(note: Notification) {
    let reachability = note.object as! Reachability
    switch reachability.connection {
    case .wifi:
        internetConnectionView.isHidden = true
    case .cellular:
        internetConnectionView.isHidden = true
    case .none:
        internetConnectionView.isHidden = false
    }
}

但是当我在运行时打开和关闭wifi时,我无法实现这一目标。

我不知道自己在想什么。

Here是我的示例项目。

1 个答案:

答案 0 :(得分:2)

之前遇到过相同的问题,要解决此问题,您需要声明

let reachability = Reachability()!

viewWillAppear函数之外,您的代码将如下所示:

let reachability = Reachability()!

override func viewWillAppear(_ animated: Bool) {

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