Reachability change notification should be called only once
Asked Answered
M

1

6

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

Mullins answered 5/8, 2015 at 5:34 Comment(0)
A
2

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

    }
}
Auberon answered 5/8, 2015 at 6:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.