可达性更改通知只应调用一次

时间:2015-08-05 05:34:14

标签: swift nsnotificationcenter reachability

我在快速项目中使用Reachability。我在AppDelegate中有以下代码

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

它会调用

func reachabilityChanged(note: NSNotification) {
}

但我的问题是,正在调用所有请求。也就是说,我正在从服务器加载图像,因此当网络可达性发生变化时,这是方法调用所有请求的方法。我希望这个方法只能被调用一次。

我还尝试在ViewController中添加此通知和方法,但它没有用。

任何帮助将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:2)

您可以添加标志以防止代码被执行,除非状态发生了如下变化:

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

    }
}