【发布时间】:2017-11-18 19:15:09
【问题描述】:
我需要从服务器下载图像并将其显示在我的应用程序中。我选择使用URLSessionDownload 协议来获取下载状态和整个过程的进度。这是我的代码:
var downloadBGTask: URLSessionDownloadTask!
var downloadBGSession: URLSession!
override func viewDidLoad() {
super.viewDidLoad()
self.downloadBGSession = {
let downloadBGSessionConfig = URLSessionConfiguration.background(withIdentifier: "downloadBGSession")
return URLSession(configuration: downloadBGSessionConfig, delegate: self, delegateQueue: OperationQueue.main)
}()
self.downloadBGTask = self.downloadBGSession.downloadTask(with: "http.. ETC .png")
self.downloadBGTask.resume()
}
协议
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
self.loadingLabel.text = "Loading (\((Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)) * 100)%)"
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Download Completed")
// How do I get the image I downloaded?
// This code below doesn't even compile
self.randomImg.image = UIImage(data: downloadTask.response!)
}
有什么建议吗?
【问题讨论】:
标签: swift url download nsurlsession