所以我有一个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中获得正在进行的下载的进度而无需启动再次下载进度(我知道再次下载会非常愚蠢)。
答案 0 :(得分:0)
最好的方法是将您的网络请求管理器代码与视图控制器分开:
didWriteData
方法中,使用NSNotificationCenter
向任何感兴趣的视图类广播通知,或者让第一个视图控制器通知第二个视图控制器是否存在。