在UITableviewCell中显示下载进度

时间:2018-01-04 11:57:20

标签: ios swift uitableview uiprogressview

我是iOS Developer。我想实现这样的功能,UITableview中有多个文件显示文件名,UIProgressView和下载按钮。我想实现如果用户点击下载按钮然后开始下载更新该单元格的UIProgressView值的文件,如果我点击另一个单元格的下载按钮,那么这两个文件应该同时下载并下载状态。如果有人有想法,请帮助我。这是我的代码

import UIKit

class PDFCell: UITableViewCell,URLSessionTaskDelegate,URLSessionDownloadDelegate {

    @IBOutlet weak var btnStartDownload: UIButton!
    @IBOutlet weak var downloadProgress: UIProgressView!
    var url:String?
    var percentageWritten: Float = 0.0
    var taskTotalBytesWritten = 0
    var taskTotalBytesExpectedToWrite = 0
    var task: URLSessionTask!
    let config = URLSessionConfiguration.background(withIdentifier: "lanet.PDFDownload")
    lazy var session: URLSession = {
        URLSession(configuration: config, delegate: self as! URLSessionDelegate, delegateQueue: OperationQueue())
    }()
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        if totalBytesExpectedToWrite > 0 {
            let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
            DispatchQueue.main.async {
                self.downloadProgress.progress = progress
            }
            debugPrint("Progress \(downloadTask) \(progress)")
        }
    }
    override func prepareForReuse() {
        super.prepareForReuse()
        self.url = ""
    }
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentDirectoryPath:String = path[0]
        let fileManager = FileManager()
        let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/file.pdf"))
        if fileManager.fileExists(atPath: destinationURLForFile.path){
            // showFileWithPath(path: destinationURLForFile.path)
        }
        else{
            do {
                try fileManager.moveItem(at: location, to: destinationURLForFile)
                // show file
                // showFileWithPath(path: destinationURLForFile.path)
            }catch{
                print("An error occurred while moving file to destination url")
            }
        }

        debugPrint("Download finished: \(location)")
        try? FileManager.default.removeItem(at: location)
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        debugPrint("Task completed: \(task), error: \(error)")
    }


    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func btnDownloadClick(_ sender: Any) {
        let url = URL(string: self.url!)!
        let task = session.downloadTask(with: url)
        task.resume()
    }
}

} enter image description here

1 个答案:

答案 0 :(得分:1)

阅读本教程以获取基本参考:https://www.raywenderlich.com/158106/urlsession-tutorial-getting-started

在部分下载进度中,您将看到

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, 
  didWriteData bytesWritten: Int64, totalBytesWritten: Int64, 
  totalBytesExpectedToWrite: Int64) {
  // 1
  guard let url = downloadTask.originalRequest?.url,
    let download = downloadService.activeDownloads[url]  else { return }
  // 2
  download.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
  // 3
  let totalSize = ByteCountFormatter.string(fromByteCount: totalBytesExpectedToWrite, countStyle: .file)
  // 4
    DispatchQueue.main.async {
    if let trackCell = self.tableView.cellForRow(at: IndexPath(row: download.track.index,
      section: 0)) as? TrackCell {
      trackCell.updateDisplay(progress: download.progress, totalSize: totalSize)
    }
  }
}