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

Swift 可达性更改通知只应调用一次,swift,nsnotificationcenter,reachability,Swift,Nsnotificationcenter,Reachability,我在swift项目中使用可达性。我在AppDelegate中有以下代码 NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability) reachability.startNotifier() 它确实叫 func reachabilityChanged(note

我在swift项目中使用可达性。我在AppDelegate中有以下代码

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

func reachabilityChanged(note: NSNotification) {
}
但我的问题是,所有的请求都需要它。也就是说,我正在从服务器加载图像,所以当网络可达性get更改时,这是方法get对所有请求的调用。我希望这个方法只调用一次

我还尝试在ViewController中添加此通知和方法,但没有成功


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

您可以添加一个标志,以防止代码被执行,除非状态发生如下更改:

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

    }
}