如何让我的iOS应用程序反应无线的变化事件

如果连接的wifinetworking发生变化(连接到新的ntwk或连接到新的ntwk),是否可以通知ios应用程序(可能不活动)?

我要build立一个应用程序(即使在非活动状态)应该得到通知时,连接到一个特定的WiFinetworking,做一些东西。

在Android中,我能够实现它使用BroadcastReceiver是否有任何这样的设施在iOS?

谢谢,Praneeth。

我们在iOS上有一个名为Reachability的类来检测任何networking闪烁/断开/连接。
可达性类可以在这里find

用法

在您的项目中添加Reachability.swift类。

这是一个Swift 2.x版本的代码,而不是3.0

对于Swift 3.x版本,请在这里查看我的答案

Swift 3.x的示例https://www.dropbox.com/sh/bph33b12tyc7fpd/AAD2pGbgW3UnqgQoe7MGPpKPa?dl=0

在你的AppDelegate创build一个Reachability类的对象

 private var reachability:Reachability! 

didFinishLaunchingWithOptions为您的networking可达性添加一个观察者

 //Network Reachability Notification check //add an observer to detect whenever network changes. NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(checkForReachability), name: ReachabilityChangedNotification, object: nil) do {self.reachability = try Reachability.reachabilityForInternetConnection() } catch { } do { try self.reachability.startNotifier() } catch{ } 

并使您的select器函数checkForReachability来检测AppDelegatenetworking更改/networking断开连接

 func checkForReachability(notification:NSNotification) { let reachability = notification.object as! Reachability if reachability.isReachable() { if reachability.isReachableViaWiFi() { print("Reachable via WiFi") } else { print("Reachable via Cellular") } } else { print("Network not reachable") } } 

无论何时出现networking变化/networking中断或networking闪烁时, Reachability类将触发ReachabilityChangedNotification ,最终将调用此用户定义的方法checkForReachability 。 所以,你可以在这里处理任何事情。

添加到上面的答案你可以使用下面的Swift 3

 let reachability = Reachability()! reachability.whenReachable = { reachability in // this is called on a background thread, but UI updates must // be on the main thread, like this: dispatch_async(dispatch_get_main_queue()) { if reachability.isReachableViaWiFi() { print("Reachable via WiFi") } else { print("Reachable via Cellular") } } } 

希望能帮助到你..

干杯!!