ios - 取消所有 Alamofire 网络事件然后新请求
问题描述
我想取消所有后台网络任务然后执行注销过程(清除 cookie、会话、用户详细信息等)。我目前不确定是否有办法等到所有网络调用都被取消后再做其他事情。
使用:Alamofire 4.7.2、Swift 3、Xcode 9.3.1、Min 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 会话管理器。
推荐阅读
- java - 如何在 jBPM 中查看自定义流程事件监听器的日志
- android-studio - 按钮为空对象引用(Android Studio)
- flutter - 如何在运行时创建两条线并计算它的颤动角度?
- c++ - MongoDB 中 javascript 函数的替代方案
- reactjs - 制作动态 crud 时是否可以使用 getStaticProps 方法?
- flutter - 错误有没有解决办法:参数'uid'不能有'null'的值,因为它的类型,但是隐含的默认值是'null'
- jenkins - 如何在 jenkinsfile 触发器中定义过滤器逻辑
- javascript - 如何在模板js文件的dom之前加载reactjs dom?
- salesforce - 如何使用 Selenium C# NUnit 框架处理 Salesforce Classic 中的画面警报
- python - 使用键获取值