简体   繁体   English

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

[英]Cancel all Alamofire network events then new request

I'd like to cancel all my background network tasks THEN do a logout process (clear cookies, session, user details etc). 我想取消所有后台网络任务,然后执行注销过程(清除cookie,会话,用户详细信息等)。 I am currently unsure of a way to wait till all network calls are canceled before doing something else. 我目前不确定在执行其他操作之前要等到所有网络呼叫都被取消的方法。

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

Current code: 当前代码:

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()
}

As expected, the logs read 符合预期,日志读取

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"...
...

There is a chance my logout process would succeed before the remaining calls are canceled and can cause other unauth issues. 在注销剩余的呼叫之前,我的注销过程可能会成功执行,并且可能导致其他未验证问题。 Would be great to wait for all to be cancelled then start the logout process. 等待所有被取消然后开始注销过程将非常棒。

Any thoughts other than my fallback idea of adding an ugly 3sec wait timer? 除了我的备用想法(添加一个丑陋的3秒等待计时器)以外,还有其他想法吗?

I've used this in my code and it works fine: 我已经在我的代码中使用了它,并且效果很好:

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

afManager is my Alamofire session manager. afManager是我的Alamofire会话管理器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM