Swift 利用Reachability监测网络连接


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

}

你可能感兴趣的:(Swift 利用Reachability监测网络连接)