ios - 如何将 NSURL session 进度添加到 TableView 单元格

标签 ios swift

我有一个基于表格 View 创建的微积分视频应用程序,我正在尝试添加离线保存视频文件的功能。我明白我想要实现的目标,但我对将进度条添加到特定单元格感到困惑:

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

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

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

最佳答案

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

  1. 在你的类下声明全局变量

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

    selectedIndex = indexPath
    
  3. 现在,在委托(delegate)方法downloadTask中赋值

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

关于ios - 如何将 NSURL session 进度添加到 TableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33380023/

相关文章:

objective-c - 突出显示 UIAlertView 中的第一个按钮

ios - 动态改变单元测试的Bundle Loader

ios - Swift 将选择器从另一个 View 触发到一个 View

ios - CoreBluetooth 广告未启动

ios - 无法在 Collection View 中创建单元格?

ios - 适用于 iOS 应用程序的 self 管理丰富的广告平台?

ios - 用于写入更大的 CSV 文件的 CHCSVWriter 内存使用情况

ios - 应用程序在后台卡住

ios - 在 Firebase 中创建一个以前不存在的新文件 - Swift

ios - 如何移动 UIView 并使用 Swift 以编程方式放置新的 UIView?