繁体   English   中英

如何在iOS上检测互联网连接的变化,委托风格?

[英]How do I detect change in internet connection on iOS, delegate style?

我需要一个功能只在系统检测到没有互联网连接时运行,然后在系统检测到互联网连接时运行另一个功能。

我在考虑这样的事情:

func onInternetConnection() {
    //Enable actions
}

func onInternetDisconnection() {
    //Disable actions, alert user
}

我还需要一种方法来检测系统何时重新连接,这样我就可以让用户知道它正在重新连接,就像在Facebook的Messenger中一样。

我怎样才能做到这一点?

我正在使用Moya / Alamofire作为我的网络层。

这适用于Alamofire

import Alamofire

// In your view did load or in app delegate do like this
let reachabilityManager = NetworkReachabilityManager()
reachabilityManager.listener = { status in

  switch status {

  case .notReachable:
    print("The network is not reachable")
    self.onInternetDisconnection()

  case .unknown :
    print("It is unknown whether the network is reachable")
    self.onInternetDisconnection() // not sure what to do for this case

  case .reachable(.ethernetOrWiFi):
    print("The network is reachable over the WiFi connection")
    self.onInternetConnection()

  case .reachable(.wwan):
    print("The network is reachable over the WWAN connection")
    self.onInternetConnection()

  }
}

Alamofire和Rechability是图书馆,具有检查互联网连接的一些功能。 你可以用它。

暂无
暂无

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

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