2016-11-13 44 views
0

我有一個應用程序,我需要從互聯網上下載文件時,我下載文件它的工作很好,但我的問題是當我按下暫停按鈕暫停下載一分鐘或更長時間我從簡歷獲得零數據從URLSessionDownloadTask恢復數據始終沒有

下面我的代碼:

@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

可能的複製(https://stackoverflow.com/questions/24215610/nsurlsessiondownloadtask-cancelbyproducingresumedata-返回null) –

+0

這是dublicate的https://stackoverflow.com/questions/24215610/nsurlsessiondownloadtask-cancelbyproducingresumedata-return-null –

回答

0

您的代碼似乎是正確的,你只需要與resumeData給init downloadData在封閉

使downloadData

var downloadData:Data! 

一個屬性,然後在你取消任務的暫停按鈕的動作,設定downloadDataresumeData

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") 
} 

注意: -嘗試一個有效的可下載URL。例如 http://www.star.uclan.ac.uk/news_and_events/news/2010020901/sdo_resolution_comparison.png

其HTTP,一定要設置傳輸安全性在[NSURLSessionDownloadTask cancelByProducingResumeData返回NULL]的Info.plist的

+0

問題是resumeData是關閉零你可以試試這個,你會看到它是零我認爲蘋果有問題 –

+0

您的網址應該對下載有效 –

+0

您的網址是什麼下載? –