【发布时间】:2019-02-12 07:07:37
【问题描述】:
我正在使用 urlsession 从服务器下载一些文件,每次下载后都会触发委托“didFinishDownloadingTo”。但我想要在所有下载完成后触发的东西。
我必须使用委托“didCompleteWithError”吗?
我如何知道是否所有文件都已下载?
func downloadPdf() {
for k in self.resultAddressServer {
let fileURL = URL(string: k)
let sessionConfig = URLSessionConfiguration.default
let operationQueue = OperationQueue()
let urlSession = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: operationQueue)
let request = URLRequest(url:fileURL!)
let downloadTask = urlSession.downloadTask(with: request)
downloadTask.resume()
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
do {
let manager = FileManager.default
let destinationURL = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent(downloadTask.originalRequest!.url!.lastPathComponent)
try? manager.removeItem(at: destinationURL)
try manager.moveItem(at: location, to: destinationURL)
print(destinationURL)
} catch {
print(error)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil {
DispatchQueue.main.async() {
self.statusLabel.text = "Download failed"
}
} else {
DispatchQueue.main.async() {
self.statusLabel.text = "Download finished"
}
}
【问题讨论】:
-
看
DispatchGroup例如stackoverflow.com/questions/52205834/… -
您似乎没有使用后台传输,但您会使用,我建议您阅读我的答案here。
标签: ios nsurlsessiondownloadtask urlsession