可达性变更通知只应调用一次 [英] Reachability change notification should be called only once

查看:63
本文介绍了可达性变更通知只应调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 swift 项目中使用了 Reachability.我在 AppDelegate 中有以下代码

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

它确实调用了

func reachabilityChanged(note: NSNotification) {
}

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

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.

我也曾尝试在 ViewController 中添加此通知和方法,但没有奏效.

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

推荐答案

你可以添加一个标志来防止代码被执行,除非状态像这样改变:

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

    }
}

这篇关于可达性变更通知只应调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆