美文网首页
Swift 利用Reachability监测网络连接

Swift 利用Reachability监测网络连接

作者: 听见_73b6 | 来源:发表于2017-07-21 13:16 被阅读0次

    <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>

    相关文章

      网友评论

          本文标题:Swift 利用Reachability监测网络连接

          本文链接:https://www.haomeiwen.com/subject/ikfekxtx.html