Reachability change notification should be called only once

依然范特西╮ 提交于 2019-12-10 16:06:28

问题


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


回答1:


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

    }
}


来源:https://stackoverflow.com/questions/31824143/reachability-change-notification-should-be-called-only-once

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