Search code examples
swiftnsnotificationcenterreachability

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


Solution

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