在所有视图控制器中获取NSURLSession下载进度

时间:2017-05-30 15:36:25

标签: nsurlsession nsurlsessiondownloadtask

所以我有一个FirstViewController我下载了一个带有进度视图的视频,并且使用此代码进展正常

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中获得正在进行的下载的进度而无需启动再次下载进度(我知道再次下载会非常愚蠢)。

1 个答案:

答案 0 :(得分:0)

最好的方法是将您的网络请求管理器代码与视图控制器分开:

  • 创建一个单独的类来管理请求,并将代理代码移到那里。
  • didWriteData方法中,使用NSNotificationCenter向任何感兴趣的视图类广播通知,或者让第一个视图控制器通知第二个视图控制器是否存在。
  • 在每个视图控制器类中,注册通知并在收到通知时,相应地更新状态。