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

问题描述

按照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()
}