简体   繁体   English

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

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

I need a function to run only when the system detects there is no internet connection, then another function to run when the system detects an internet connection. 我需要一个功能只在系统检测到没有互联网连接时运行,然后在系统检测到互联网连接时运行另一个功能。

I'm thinking of something like this: 我在考虑这样的事情:

func onInternetConnection() {
    //Enable actions
}

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

I will also need a way to detect when the system is reconnecting, so I can let the user know it's reconnecting, like in Facebook's Messenger. 我还需要一种方法来检测系统何时重新连接,这样我就可以让用户知道它正在重新连接,就像在Facebook的Messenger中一样。

How can I do this? 我怎样才能做到这一点?

I'm using Moya/Alamofire for my network layer. 我正在使用Moya / Alamofire作为我的网络层。

This works in case of 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 and Rechability are library and that have some features to check internet connection. Alamofire和Rechability是图书馆,具有检查互联网连接的一些功能。 You can use one from that. 你可以用它。

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

相关问题 如何检测是否没有互联网连接 - How to detect if there no internet connection 如何检测我在iOS上使用Internet? - How to detect I am using the Internet on iOS? IOS 如果设备没有互联网连接如何检测它并显示相应的文本 - IOS If device has no internet connection how to detect it and show an according text 连接到wifi但没有intenernet时如何检测互联网连接:iOS - How to detect internet connection when connected to wifi but no intenernet: iOS 如何在 iOS 上使用 Phonegap 正确检测方向变化? - How do I correctly detect orientation change using Phonegap on iOS? 在iOS上检测Internet连接的最简单方法是? - Easiest way to detect Internet connection on iOS? 如何在iOS中检测到互联网连接丢失5秒而TCP连接丢失的情况 - how to detect tcp connection lost while internet connection lost for 5 sec in the ios iOS Bluetooth Central,可靠的代理方法可检测连接/断开 - iOS Bluetooth Central, Reliable Delegate Method to Detect Connection/Disconnect 如何在 iOS 或 macOS 上检查活动的互联网连接? - How can I check for an active Internet connection on iOS or macOS? 如何在 iOS 上检测设备的方向? - How Do I detect the orientation of the device on iOS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM