内容简介:翻译自:https://stackoverflow.com/questions/39094022/swift-alamofire-cancel-previous-request
我有一个NetworkRequest类,我的所有alamofire请求都在这里:
class NetworkRequest { static let request = NetworkRequest() var currentRequest: Alamofire.Request? let dataManager = DataManager() let networkManager = NetworkReachabilityManager() let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT func downloadData<T: Film>(slug: String, provider: String, section: String, dynamic: String, anyClass: T, completion: ([T]?) -> Void ) { var token: String = "" if LOGGED_IN == true { token = "\(NSUserDefaults.standardUserDefaults().valueForKey(TOKEN)!)" } let headers = [ "Access": "application/json", "Authorization": "Bearer \(token)" ] let dataUrl = "\(BASE_URL)\(slug)\(provider)\(section)\(dynamic)" print(headers) print(dataUrl) if networkManager!.isReachable { currentRequest?.cancel() dispatch_async(dispatch_get_global_queue(priority, 0)) { if let url = NSURL(string: dataUrl) { let request = Alamofire.request(.GET, url, headers: headers) request.validate().responseJSON { response in switch response.result { case .Success: if let data = response.result.value as! [String: AnyObject]! { let receivedData = self.dataManager.parseDataToFilms(data, someClass: anyClass) completion(receivedData) } case .Failure(let error): print("Alamofire error: \(error)") if error.code == 1001 { self.goToNoConnectionVC() } print("canceled") } } } } } else { goToNoConnectionVC() } } }
我需要取消以前的downloadData请求,当新的请求启动时,尝试使用currentRequest?.cancel()取消,但它没有帮助.
已经尝试使用NSOperationsBlock取消操作,但它不会取消当前操作.
我现在阻止UI,因此用户无法发送另一个请求.但这不正确,以后会导致一些错误……
请帮助
现在在Alamofire 4上Alamofire.Manager.sharedInstance.session不可用你应该使用 this
解决方案:
let sessionManager = Alamofire.SessionManager.default sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in dataTasks.forEach { $0.cancel() } uploadTasks.forEach { $0.cancel() } downloadTasks.forEach { $0.cancel() } }
如果您想取消(暂停,恢复)特定请求,您可以检查.forEach块中的请求URL,如下所示:
dataTasks.forEach { if ($0.originalRequest?.url?.absoluteString == url) { $0.cancel() } }
翻译自:https://stackoverflow.com/questions/39094022/swift-alamofire-cancel-previous-request
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 封装 axios 取消重复请求
- axios重复点击取消上一次请求封装
- ios afnetworking取消正在进行的网络请求
- Android中用Kotlin Coroutine(协程)和Retrofit进行网络请求和取消请求
- [React.js]组件卸载如何自动取消异步请求
- Git 设置和取消代理
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。