URLSession dataTask を使用して、結果ハンドラーとして URLSessionDownloadDelegate を含むファイルをダウンロードしています。ただし、urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)呼び出されることはありません。代わりにurlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)、エラーがゼロになります。代わりに completionHandler メソッドを使用してタスクを実行すると、すべてが機能します。
これが私のコードです:
import UIKit
class ViewController: UIViewController, URLSessionDownloadDelegate {
var downloadTask: URLSessionDataTask?
override func viewDidLoad() {
super.viewDidLoad()
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
let url = URL(string: "https://unsplash.it/200/300/?random")!
//downloadTask = session.dataTask(with: request)
downloadTask = session.dataTask(with: url)
downloadTask!.resume()
}
@IBAction func cancelButtonTapped(_ sender: Any) {
downloadTask?.cancel()
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
print("session: didBecomeInvalidWithError: \(error?.localizedDescription)")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Your data is here!")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten / totalBytesExpectedToWrite)
print("Making progress: \(progress)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("session: task: didCompleteWithError: \(error?.localizedDescription)")
session.finishTasksAndInvalidate()
}
}
シミュレーターの出力は
session: task: didCompleteWithError: nil
session: didBecomeInvalidWithError: nil
前もって感謝します。