如何将NSURL会话进度添加到表视图单元格中



我有一个基于表视图创建的Calculus Video应用程序,我正在尝试添加离线保存视频文件的功能。我理解我想要实现的目标,但我被添加到特定单元格的进度条难住了:

目前,下载是通过点击附件按钮开始的。我有以下方法

override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
        //Code to save Video to Documents directory goes here
        let currentVideo = videos[indexPath.section][indexPath.row]
        guard currentVideo.saved == false else {
            print("Video is already saved")
            return
        }
        guard let url = currentVideo.url else {
            print("Video not found...url is invalid")
            return
        }
        guard currentVideo.downloading == false else {
            print("Video is already downloading")
            return
        }
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
            delegate: self,
            delegateQueue: NSOperationQueue.mainQueue())
        let downloadTask = session.downloadTaskWithURL(url)
        downloadTask.resume()
}

现在,我正在实现NSURLSessionDownloadDelegate方法,其中相关的方法在下面

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
    print(progress) //this works and shows progress
}

现在,我想做的就是更新属性

currentVideo.progress = progress  
//where currentVideo is the video for the cell that was tapped

问题是我不知道如何在这个委托方法中获取当前视频。我试图以某种方式弄清楚如何使用downloadTask.taskIdentifier或类似的东西,但我无法弄清楚。有人能给我指正确的方向吗?

您可以按照以下方式进行尝试。

  1. 在类下声明全局变量

    var selectedIndex:NSIndexPath!
    
  2. 然后在accessoryButtonTappedForRowWithIndexPath方法中

    selectedIndex = indexPath
    
  3. 现在,在委托方法downloadTask中分配值

    let currentVideo = videos[selectedIndex.section][selectedIndex.row]
    currentVideo = // Your value
    

最新更新