从 URLSessionDownloadTask 恢复数据 始终为零

Posted

技术标签:

【中文标题】从 URLSessionDownloadTask 恢复数据 始终为零【英文标题】:Resume Data from URLSessionDownloadTask Always nil 【发布时间】:2016-11-13 10:01:41 【问题描述】:

我有一个应用程序,当我下载文件时,我需要从互联网下载文件,但我的问题是当我按下暂停按钮以暂停下载一分钟或更长时间时,我从恢复数据中得到零

下面是我的代码:

@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)
                        

请帮帮我

谢谢大家

【问题讨论】:

NSURLSessionDownloadTask cancelByProducingResumeData return null的可能重复 这是***.com/questions/24215610/…的副本 【参考方案1】:

您的代码似乎是正确的,您只需要在关闭时使用resumeData 来初始化downloadData

创建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中设置Transport Security

【讨论】:

问题是 resumeData 是关闭的 nil 你可以试试这个,你会看到它是 nil 我认为苹果有问题 你的网址应该是有效的下载 你的下载地址是什么? 请先给出网址 @HaiderAhmed 你检查过浏览器上的网址是播放歌曲还是下载歌曲吗

以上是关于从 URLSessionDownloadTask 恢复数据 始终为零的主要内容,如果未能解决你的问题,请参考以下文章

URLSessionDownloadTask:取消写入数据

URLSessionDownloadTask 启动时调用的委托方法是啥?

无法从 URLSessionTaskDelegate 获取数据

后台应用刷新对后台 URLSession 有影响吗?

完成后在后台下载并唤醒应用程序

如何在闭包中使用 self 来防止内存泄漏