2

我有以下代码来确定是否有互联网连接。这段代码工作正常。我怎么知道我是否突然失去了连接

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

可达性类是否具有报告连接是否断开的功能。如果无法通过可达性来处理该问题,那么另一种选择是什么

4

2 回答 2

5

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

//

当状态改变时,这个方法被调用

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

//

为避免崩溃不要忘记取消注册

reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
于 2018-05-28T17:28:10.827 回答
1

对于 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"))

完成监控后:

monitor.cancel()
于 2021-03-30T20:06:05.670 回答