2017-05-30 71 views
0

所以我有一個FirstViewController在那裏我下載與發展觀爲視頻和進度使用此代碼得到NSURLSession下載所有視圖控制器進步

func startDownloading() { 
    let download = Downloads(url: videoUrl!.absoluteString!) 
    download.downloadTask = self.downloadsSession.downloadTaskWithURL(videoUrl!)      
    download.downloadTask!.resume() 
    download.isDownloading = true 

} 

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { 
    // 1 
    print("URLSession Completed for url \(downloadTask.originalRequest?.URL?.absoluteString)") 

    if let originalURL = downloadTask.originalRequest?.URL?.absoluteString, 
     destinationURL = localFilePathForUrl(originalURL) { 

     let fileManager = NSFileManager.defaultManager() 
     do { 
      try fileManager.removeItemAtURL(destinationURL) 
     } catch { 
      // Non-fatal: file probably doesn't exist 
     } 
     do { 
      try! fileManager.copyItemAtURL(location, toURL: destinationURL) 
     } catch let error as NSError { 
      print("Could not copy file to disk: \(error.localizedDescription)") 
     } 
    } 
} 

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 

    print("URLSession inProgress \(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite))") 


    if let downloadUrl = downloadTask.originalRequest?.URL?.absoluteString, 
     let download = activeDownloads[downloadUrl] { 
     //THIS SETS THE PROGRESS 
     download.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 


     self.downloadView.state = .Downloading 
      self.downloadView.setProgress(Double(totalSize)!, animated: true)  

    } 
} 

現在這個代碼更新FirstViewControllers downloadView.progress工作正常正確,但我想要的是當我去SecondViewController我應該得到在SecondVC這次正在進行的下載的進展也沒有再次開始下載進度(我知道再次下載將是非常愚蠢的)。

回答

0

最好的辦法是從視圖控制器分開您的網絡請求管理器代碼:

  • 創建一個單獨的類來管理的要求,並有移動你的委託代碼。
  • didWriteData方法中,使用NSNotificationCenter將通知廣播到任何感興趣的視圖類,或者讓您的第一個視圖控制器通知第二個視圖控制器(如果存在)。
  • 在每個視圖控制器類中,註冊通知,並在收到通知時相應地更新狀態。
+0

我在想同樣的事情,但找不到任何人使用它,你認爲這是最好的方式嗎? – TestDjay

相關問題