【问题标题】:get NSURLSession download progress in all view controllers获取所有视图控制器中的 NSURLSession 下载进度
【发布时间】:2017-05-30 15:36:24
【问题描述】:

所以我有一个 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 中获得这个正在进行的下载的进度再次下载进度(我知道再次下载会很愚蠢)。

【问题讨论】:

    标签: nsurlsession nsurlsessiondownloadtask


    【解决方案1】:

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

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

    【讨论】:

    • 我也在考虑同样的事情,但找不到任何人在使用它,你认为这是最好的方法吗?
    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多