gpt4 book ai didi

swift, alamofire 取消之前的请求

转载 作者:IT王子 更新时间:2023-10-29 05:39:41 25 4
gpt4 key购买 nike

我有一个 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()
}
}
}

我需要取消之前的下载数据请求,当新请求开始时,尝试使用 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 block 中检查请求 url,如下所示:

dataTasks.forEach {
if ($0.originalRequest?.url?.absoluteString == url) {
$0.cancel()
}
}

关于swift, alamofire 取消之前的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39094022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com