簡體   English   中英

在UITableviewCell中顯示下載進度

[英]Show download progress in UITableviewCell

我是iOS開發人員。我要實現的功能是,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()
    }
}

} 在此處輸入圖片說明

瀏覽本教程以獲取基本參考: 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)
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM