ios - ReachabilitySwift 有什么问题?

标签 ios swift reachability

在我的 viewDidLoad() 函数中,我调用了这个方法:

//MARK: Reachability
func startReachability(){
    //declare this property where it won't go out of scope relative to your listener
    do{
        let reachability = try Reachability.reachabilityForInternetConnection()

        reachability.whenReachable = { reachability in
            // this is called on a background thread, but UI updates must
            // be on the main thread, like this:
            dispatch_async(dispatch_get_main_queue()) {
                if reachability.isReachableViaWiFi() {
                    print("Reachable via WiFi")
                } else {
                    print("Reachable via Cellular")
                }
            }
        }
        reachability.whenUnreachable = { reachability in
            // this is called on a background thread, but UI updates must
            // be on the main thread, like this:
            dispatch_async(dispatch_get_main_queue()) {
                print("Not reachable")
            }
        }

        try reachability.startNotifier()

    } catch {
        print("Unable to start notifier")
    }
}

但它不起作用。它只调用一次 whenReachable()whenUnreachable() 并且当我关闭和打开 Wi-Fi 时它什么也不做。

最佳答案

我需要对 Reachability 实例的强烈引用!所以我应该在类里面声明它。

关于ios - ReachabilitySwift 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39568144/

相关文章:

ios - 具有多个原型(prototype)单元格的 Collection View 以及在 MVVM 下处理它们的通用方法

ios - 将文本字段输入更改为在 UIDatePicker 中选择的日期(当值更改时)

swift - xcworkspace 文件的困惑

ios - ASINetworkQueue正确使用和存储

ios - NSRegularExpression 中的命名捕获组 - 获取范围组的名称

ios - NSDate 具有相反的 AM/PM 值

ios - 无法在 Swift 中从 Facebook iOS SDK 捕获城市和国家/地区值

ios - 实现 tapjoy 分析代码后可达性代码中的应用程序崩溃

ios - 在 Internet 连接可用后做某事的最佳方法

ios - 将线性转换为 Apple Display P3 色彩空间的方程式,反之亦然