我有一个应用程序,我需要从互联网上下载文件,当我下载文件它的工作正常,但我的问题是当我按下暂停按钮暂停下载一分钟或更长时间我从简历数据< / p>
以下我的代码:
@IBAction func startDownloading(_ sender: UIButton)
{
isDownload = true
sessionConfig = URLSessionConfiguration.default
let operationQueue = OperationQueue.main
session = URLSession.init(configuration: sessionConfig, delegate: self, delegateQueue: operationQueue)
let url = URL(string: "www.example.com")
downloadTask = session.downloadTask(with: url!)
downloadTask.resume()
}
@IBAction func pause(_ sender: UIButton)
{
if downloadTask != nil && isDownload
{
self.downloadTask!.cancel(byProducingResumeData: { (resumeData) in
// here is the nil from the resume data
})
isDownload = false
downloadTask = nil
pasueBtnOutlet.setTitle("Resume", for: .normal)
}
if !isDownload && downloadData != nil
{
downloadTask = session.downloadTask(withResumeData: downloadData as Data)
downloadTask.resume()
isDownload = true
downloadData = nil
pasueBtnOutlet.setTitle("Pause", for: .normal)
}
}
请帮帮我
感谢所有
答案 0 :(得分:0)
您的代码似乎是正确的,您只需在关闭时使用downloadData
初始化resumeData
制作downloadData
var downloadData:Data!
然后在您取消任务的暂停按钮操作中,将downloadData
设置为resumeData
self.downloadTask!.cancel(byProducingResumeData: { (resumeData) in
// here is the nil from the resume data
// You have to set download data with resume data
self.downloadData = resumeData
})
为了检查进度和完成情况,请实施这些URLSessionDownloadDelegate
代理
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print(Int(progress * 100))
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Downloading done")
}
注意: - 尝试有效的可下载网址。例如 http://www.star.uclan.ac.uk/news_and_events/news/2010020901/sdo_resolution_comparison.png
其http,请务必在Info.plist中设置传输安全性