简体   繁体   中英

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). 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+

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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