How to make my ios app reactive to wifi change events

南笙酒味 提交于 2019-12-20 02:11:55

问题


Can an ios app (possibly not active) be notified if there is a change in wifi network connected to(getting disconnected from, or getting connected to new ntwk)?

I am to build an app that (even in inactive state) should get notified when connected to a particular wifi network and do some stuff.

In android i was able to achieve it using BroadcastReceiver is there any such facility in ios?

Thanks, Praneeth.


回答1:


We have a class called Reachability in iOS for detecting any network flicker/disconnection/connection.
Reachability class can be found here

Usage

Add Reachability.swift class in your project.

This is a Swift 2.x version code and not 3.0

For Swift 3.x version check my answer here

Sample of Swift 3.x https://www.dropbox.com/sh/bph33b12tyc7fpd/AAD2pGbgW3UnqgQoe7MGPpKPa?dl=0

In your AppDelegate make an object of Reachability class

private var reachability:Reachability!

In didFinishLaunchingWithOptions add a observer for your network reachability

//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{
}

And make your selector function checkForReachability to detect network changes/network disconnects in AppDelegate

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")
    }
}

Whenever there is a network change/network break or whenever network will flicker, the Reachability class will fire a ReachabilityChangedNotification which will ultimately call this user defined method checkForReachability. So, you can handle anything here.




回答2:


Adding to the above answer you can use the following for 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")
        }
    }
}

Hope it helps..

Cheers!!



来源:https://stackoverflow.com/questions/39983776/how-to-make-my-ios-app-reactive-to-wifi-change-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!