gpt4 book ai didi

ios - 如果我在页面完成之前退出页面,如何取消 URLSession.shared.dataTask?

转载 作者:行者123 更新时间:2023-12-04 17:24:07 27 4
gpt4 key购买 nike

遵循 https://stackoverflow.com/a/27712427/3286489 的建议,我可以执行如下异步下载,并且在viewDidLoad期间被调用.

    func loadItems(tuple : (name : String, imageURL : URL)) {
print("Download Started")
URLSession.shared.dataTask(with: tuple.imageURL, completionHandler :
{ data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? tuple.imageURL.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { [weak self] in
self?.displayFlag(data: data, title: tuple.name)
}
}).resume()
}
这一切都很好。我的问题是,如果下载速度很慢,然后我退出页面,我如何以及在哪里( viewDidUnload ?看起来已经弃用了)可以取消获取(图像下载)任务吗?

最佳答案

保存 URLSessionTask引用:

private weak var task: URLSessionTask?

func loadItems(name: String, url: URL) {
let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async {
self?.displayFlag(data: data, title: name)
}
}
task.resume()
self.task = task
}
然后,在解雇时, cancel它:
deinit {
task?.cancel()
}

关于ios - 如果我在页面完成之前退出页面,如何取消 URLSession.shared.dataTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64494031/

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