如何检测 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 是库,具有一些检查互联网连接的功能。您可以使用其中的一个。
我需要一个仅当系统检测到没有互联网连接时 运行 的函数,然后当系统检测到互联网连接时另一个函数 运行 。
我在想这样的事情:
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 是库,具有一些检查互联网连接的功能。您可以使用其中的一个。