简体   繁体   English

互联网连接状态快速可达

[英]Internet connection status swift reachability

I have the following code to determine whether if there is an internet connection or no.我有以下代码来确定是否有互联网连接。 This code works fine.这段代码工作正常。 How Can I know if I suddenly lost the connection我怎么知道我是否突然失去了连接

  var reachability:Reachability?
  reachability = Reachability()
  self.reachability  = Reachability.init()
    if((self.reachability!.connection) != .none)
    {
        print("Internet available")
    }

Does reachability class has a feature that reports if the connection is broken.可达性类是否具有报告连接是否断开的功能。 If there is no way to handle that issue with reachability what is the other option如果无法通过可达性处理该问题,还有什么其他选择

Declare this in AppDelegate / Vc在 AppDelegate / Vc 中声明

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

// //

when status is changed this method is called当状态改变时调用此方法

@objc func reachabilityChanged(note: Notification) {

   let reachability = note.object as! Reachability

    switch reachability.connection {
     case .wifi:
         print("Reachable via WiFi")
     case .cellular:
         print("Reachable via Cellular")
     case .none:
         print("Network not reachable")
    }
}

// //

to avoid crashes don't forget to un register为避免崩溃,不要忘记取消注册

reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)

For iOS12+, I would use NWPathMonitor which makes monitoring network change super easy:对于 iOS12+,我会使用 NWPathMonitor,这使得监控网络变化变得非常容易:

import Network

let monitor = NWPathMonitor()

monitor.pathUpdateHandler = { path in
    if path.status != .satisfied {
        // Lost connection, do your thing here
    }
}
monitor.start(queue: DispatchQueue(label: "network_monitor"))

When you are done monitoring:完成监控后:

monitor.cancel()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM