Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reachability change notification should be called only once

I'm using Reachability in my swift project. I had below code in AppDelegate

NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
reachability.startNotifier()

It does call

func reachabilityChanged(note: NSNotification) {
}

But my problem is that, it is being called for all the request. That is, I'm loading images from the server, so when network reachability get's change this is method get's call for all the request. I want that this method should be called only once.

I had also tried to add this notification and method in ViewController, but it didn't work.

Any help will be appreciated. Thanks in advance

like image 493
Ankita Shah Avatar asked Oct 30 '22 22:10

Ankita Shah


1 Answers

You can add a flags to prevent the code from being executed unless the state has changed like this:

var connectionState = "Connected"
let connectedState = "Connected"
let notConnectedState = "notConnected"

func checkForReachability(notification:NSNotification)
{

    let networkReachability = notification.object as! Reachability;
    var remoteHostStatus = networkReachability.currentReachabilityStatus()

    if remoteHostStatus.value == NotReachable.value && connectedState == connectedState {

        connectionState = notConnectedState
        println("State Changed Not Connected")

    } else if remoteHostStatus.value == ReachableViaWiFi.value && connectedState == notConnectedState {

        connectionState = connectedState
        println("State Changed Connected")

    }
}
like image 89
Firas Avatar answered Nov 18 '22 03:11

Firas