如果互联网连接丢失,如何停止功能执行

时间:2016-05-03 17:23:18

标签: swift connection reachability

我使用名为RealReachability的lib,实时获取当前的可达性状态!

我有一个从我的服务器获取数据的功能。

现在看起来像这样:

    RealReachability.sharedInstance().reachabilityWithBlock { (status: ReachabilityStatus) in
        switch status {
        case .RealStatusNotReachable:
            break
        default:
        operationQueue.addOperationWithBlock {
            GettingDataFromServer() }
        }
    }

RealReachability也可以在可达性状态发生变化时发送通知。看起来像这样:

var operationQueue = NSOperationQueue()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyController.networkChanged), name: kRealReachabilityChangedNotification, object: nil)

  func networkChanged(notification: NSNotification) {
    print("NetworkChanged")

    let status = RealReachability.sharedInstance().currentReachabilityStatus()

    switch status {
    case .RealStatusNotReachable:
        print("try to stop Operation")
        operationQueue.cancelAllOperations()
        ShowInternetConnectionErrorView()

    default:
        print("Internet OK!")
    }



}

当可达性状态更改为.RealStatusNotReachable

时,我需要什么来停止GetDataFromServer()函数的执行?

1 个答案:

答案 0 :(得分:0)

RealReachability library中,GLobalRealReachability是共享实例。因此,您可以查询此类以了解当前状态:

let status = GLobalRealReachability.currentReachabilityStatus
if (status == RealStatusNotReachable)
{
    //do whatever you want when internet is not reachable
    // To stop your observer you can do:
    NSNotificationCenter.defaultCenter().removeObserver(self)
    // ...or by specify the exact name:
    NSNotificationCenter.defaultCenter().removeObserver(self, name: kRealReachabilityChangedNotification, object: nil)
}

在你的代码中直接停止你的操作:

全球变种:

var  operation1 : NSBlockOperation!

self.operation1 : NSBlockOperation = NSBlockOperation ({
            GettingDataFromServer() 
})

并修改您的代码:

RealReachability.sharedInstance().reachabilityWithBlock { (status: ReachabilityStatus) in
        switch status {
        case .RealStatusNotReachable:
            if operationQueue.operations.containsObject(operation1) {
                 for op in operationQueue.operations {
                     if op == operation1 {
                        op.cancel()
                     }
                 }
            }
            break
        default:
            operationQueue.addOperation(operation1)
    }

<强>更新: 就像我在上一次评论中报告一样,尝试声明:

var operationQueue = NSOperationQueue()

在共享实例类或appDelegate上。

例如关于你可以做的最后一个解决方案:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable

并在项目的任何地方使用您的队列。