Наблюдать или отслеживать индикатор выполнения на каждой функции Swift - PullRequest
1 голос
/ 04 февраля 2020

Я реализовал tableView с пользовательской ячейкой для встреч с индикатором выполнения для отслеживания. Как я могу наблюдать или отслеживать индикатор выполнения на быстрых функциях? На самом деле я не понимаю, как сохранить данные о прогрессе и как их показать? У меня есть иерархия функций, как это.

  1. назначение вызова (дата)
    • назначениеDetail ()
    • firmDetails ()
    • unitData ()
    • unitDataHistory ()
    • unitDataImages ()
    • downloadPDFTask (pdfURL: String)

Все функции выполняются очень эффективно, но функция downloadPDFTask занимает мало время для файлов. Скачать PDF использует alamofire и иметь прогресс только хотят отслеживать его.

Как отслеживать индикатор выполнения?

downloadPDFTask код:

@objc public func downloadFile(url:String, filetype: String, callback:@escaping (_ success:Bool, _ result:Any?)->(Bool)) -> Void {
var destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
if filetype.elementsEqual(".pdf"){
            destination = { _, _ in
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let downloadFileName = url.filName()
                let fileURL = documentsURL.appendingPathComponent("\(downloadFileName).pdf")
                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }
        } 

        self.request = Alamofire.download(
            url,
            method: .get,
            parameters: nil,
            encoding: JSONEncoding.default,
            headers: nil,
            to: destination).downloadProgress(closure: { (progress) in

                print(progress)
                print(progress.fractionCompleted)

            }).response(completionHandler: { (DefaultDownloadResponse) in
                callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.path)
           print(DefaultDownloadResponse)
                })
    }

Обновить код и изображение:

var downloadProgress : Double = 0.0 {
      didSet {
        for indexPath in self.tableView.indexPathsForVisibleRows ?? [] {
        if let cell = self.tableView.cellForRow(at: indexPath) as? DownloadEntryViewCell {
            cell.individualProgress.setProgress(Float(downloadProgress), animated: true) //= "\(downloadProgress)" // do whatever you want here
            print(downloadProgress)
            }
        }
      }
  }

Ответы [ 2 ]

2 голосов
/ 04 февраля 2020

Добавьте наблюдателя свойства downloadProgress

var downloadProgress : Double = 0.0 { 
    didSet { 
        self.tableView.reloadRows(at: [IndexPath(item: yourRow, section: 0)], with: .none) // do whatever you want here
    }
}

, а затем присвойте ему значение progess. didSet будет вызываться каждый раз, когда изменяется значение прогресса.

    self.request = Alamofire.download(
        url,
        method: .get,
        parameters: nil,
        encoding: JSONEncoding.default,
        headers: nil,
        to: destination).downloadProgress(closure: { (progress) in

            print(progress)
            print(progress.fractionCompleted)
            self.downloadProgress = progress // assign the value here. didSet will be called everytime the progress value changes.
        }).response(completionHandler: { (DefaultDownloadResponse) in
            callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.path)
       print(DefaultDownloadResponse)
            })
1 голос
/ 04 февраля 2020

Вы уже вызываете API-интерфейс Progress, поэтому единственное, что вам нужно сделать, это предоставить его вызывающей стороне вашего метода.


@objc public func downloadFile(url:String, filetype: String, updateProgress: @escaping (_ fraction: Double)->(Void), callback:@escaping (_ success:Bool, _ result:Any?)->(Bool)) -> Void {
var destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
if filetype.elementsEqual(".pdf"){
            destination = { _, _ in
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let downloadFileName = url.filName()
                let fileURL = documentsURL.appendingPathComponent("\(downloadFileName).pdf")
                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }
        } 

        self.request = Alamofire.download(
            url,
            method: .get,
            parameters: nil,
            encoding: JSONEncoding.default,
            headers: nil,
            to: destination).downloadProgress(closure: { (progress) in

                print(progress)
                print(progress.fractionCompleted)
                // Call the update closure
                updateProgress(progress.fractionCompleted)

            }).response(completionHandler: { (DefaultDownloadResponse) in
                callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.path)
           print(DefaultDownloadResponse)
                })
    }

Таким образом, вы добавляете замыкание, которое получает Double от 0 до 1, указывающий прогресс. В своем звонке вы передаете Closire, который обновляет ваш индикатор выполнения.

...