6

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

我在想这样的事情:

func onInternetConnection() {
    //Enable actions
}

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

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

我怎样才能做到这一点?

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

4

2 回答 2

4

这适用于 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()

  }
}
于 2017-05-09T09:59:22.190 回答
0

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

于 2017-05-09T12:37:34.820 回答