代码之家  ›  专栏  ›  技术社区  ›  Ahmed

互联网连接状态快速可达性

  •  1
  • Ahmed  · 技术社区  · 6 年前

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

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

    可到达性类是否具有一个在连接断开时报告的功能。如果没有办法用可达性来处理这个问题,另一个选择是什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Shehata Gamal    6 年前

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