我使用名为 RealReachability 的库来实时获取当前可达性状态!
我有一个从我的服务器获取数据的功能。
现在它看起来像这样:
RealReachability.sharedInstance().reachabilityWithBlock { (status: ReachabilityStatus) in
switch status {
case .RealStatusNotReachable:
break
default:
operationQueue.addOperationWithBlock {
GettingDataFromServer() }
}
}
当 Reachability 状态改变时,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 时,我需要什么来停止 GettingDataFromServer() 函数的执行
最佳答案
在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)
}
在您的代码中,您可以直接停止您的 nsoperation:
全局变量:
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
并在项目周围的任何地方使用您的队列。
关于swift - 如果互联网连接丢失,如何停止函数执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37010526/