首页 > 解决方案 > 取消所有 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 秒等待计时器的后备想法之外,还有什么想法吗?

标签: iosswiftalamofire

解决方案


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

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

afManager 是我的 Alamofire 会话管理器。


推荐阅读