簡體   English   中英

取消所有Alamofire網絡事件,然后取消新請求

[英]Cancel all Alamofire network events then new request

我想取消所有后台網絡任務,然后執行注銷過程(清除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會話管理器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM