如何使用 Reachability 在 运行 时间检查互联网连接的网络连接变化?

How to check network connectivity changes for internet connection at run time with Reachability?

我正在使用 this 库来检查可达性

下面是我的示例代码:

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 是我的示例项目。

之前遇到过同样的问题,要解决它你需要声明

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