Swift 利用Reachability监测网络连接

2017-07-21  本文已影响0人  听见_73b6

<pre>
class ReachabilityHelper {
static func reach(_ reachable: @escaping (_ wifi:Bool) -> Void, unreachable: @escaping () -> Void) {

    let reachability = Reachability()!
    
    reachability.whenReachable = { reachability in
        // this is called on a background thread, but UI updates must
        // be on the main thread, like this:
       DispatchQueue.main.async {
            if reachability.isReachableViaWiFi {

// print("Reachable via WiFi")
reachable(true)
} else {
// print("Reachable via Cellular")
reachable(false)
}

        }
    }
    reachability.whenUnreachable = { reachability in
        // this is called on a background thread, but UI updates must
        // be on the main thread, like this:
        DispatchQueue.main.async {

// print("Not reachable")
unreachable()
}

    }
    
    do {
        try reachability.startNotifier()
    } catch {

// print("Unable to start notifier")
}
}

}
</pre>

上一篇下一篇

猜你喜欢

热点阅读