当我从另一个控制器回来时,进度栏未显示更新的值

时间:2018-10-09 07:22:34

标签: swift uitableview download delegates nsnotificationcenter

我想在表格视图单元格中显示下载进度,但是当我从另一个控制器回来时,进度条将不会在单元格中显示更新的值。它只会显示最后收到的值。我尝试使用NOTIFICATION CENTER和DELEGATE更新进度值,但两者均无法正常工作。我该如何实现。请帮助我。

这是我在项目中实现的代码。 startDownloading方法在我的项目的通用类中不可用

func startDownloading(url: String, indexpath: IndexPath) {
if (NetworkReachabilityManager()!.isReachable) {

    let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)

    Alamofire.download(URL(string: url)!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil, to: destination).downloadProgress(queue: .main) { (progress) in
        DispatchQueue.main.async {
            print("download: \(progress)")
            NotificationCenter.default.post(name: Notification.Name("downloadSong"), object: ["row": indexpath.row, "value": progress])
        }
        }.response(queue: .global(qos: .background)) { (response) in
            if let destinationPath = response.destinationURL {
                NotificationCenter.default.post(name: Notification.Name("downloadSong"), object: indexpath.row)
                NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "downloadSong"), object: nil)
            }
    }
} else {
    print("Please connect to Internet.")
}
}

以及在UIViewcontroller类中实现的以下方法:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCell(withIdentifier:"cellReuseIdentifier") as! AllSongsTableCell
    cell.downloadTapped = {
        NotificationCenter.default.addObserver(self, selector: #selector(self.updateCell(_:)), name: NSNotification.Name("downloadSong"), object: nil)
        startDownloading(url: "song-url", indexpath: indexPath)
    }
}

//Observer Method
@objc func updateCell(_ notification: NSNotification) {
    if let object = notification.object as? [String: Any] {
        DispatchQueue.main.async {
            if let cell = self.allSongsTable.cellForRow(at: IndexPath(row: object["row"] as! Int, section: 0)) as? AllSongsTableCell {
                let value = object["value"] as! Double
                cell.graphView.value = UICircularProgressRing.ProgressValue(value)
            }
            self.allSongsTable.reloadRows(at: [IndexPath(row: object, section: 0)], with: .none)
        }
    }
}

0 个答案:

没有答案