取消所有Alamofire网络事件,然后取消新请求



我想取消我所有的后台网络任务,然后执行注销过程(清除cookie,会话,用户详细信息等(。 我目前不确定是否有一种方法可以等到所有网络调用都被取消后再执行其他操作。

使用: Alamofire 4.7.2, Swift 3, Xcode 9.3.1, minin iOS 9+

当前代码:

Alamofire.SessionManager.default.session.getAllTasks { (tasks) in
print("tasks to cancel: (tasks.count)")
// cancel all network tasks
tasks.forEach {
$0.cancel()
print("canceling network task")
}
// ToDo need to wait for all tasks to be canceled first
doLogout()
}

正如预期的那样,日志读取

tasks to cancel: 5
canceling network task
canceling network task
canceling network task
canceling network task
canceling network task
do logout
Making request Logout
POST : https://.../logout
GET :  https://... back  with error:  Error Domain=NSURLErrorDomain Code=-999 "cancelled"...
GET :  https://... back  with error:  Error Domain=NSURLErrorDomain Code=-999 "cancelled"...
GET :  https://... back  with error:  Error Domain=NSURLErrorDomain Code=-999 "cancelled"...
GET :  https://... back  with error:  Error Domain=NSURLErrorDomain Code=-999 "cancelled"...
GET :  https://... back  with error:  Error Domain=NSURLErrorDomain Code=-999 "cancelled"...
...

在取消剩余呼叫之前,我的注销过程可能会成功,并可能导致其他非身份验证问题。等待所有取消然后开始注销过程会很棒。

除了我添加丑陋的 3 秒等待计时器的后备想法之外,还有其他想法吗?

我已经在我的代码中使用了它,它工作正常:

afManager.session.getAllTasks { (tasks) in
print(tasks)
tasks.forEach{ $0.cancel() }
}

afManager是我的Alamofire会话管理器。

最新更新