如何更新另一个 UIViewController 上的进度视图 - SWIFT?

How to update a progress view that is on another UIViewController - SWIFT?

我有一个 UITableViewController 嵌入在 UINavigationController 中。当我点击一行时,我试图上传一个文件。为了显示此上传的进度,我决定使用自定义弹出窗口(另一个 UIViewController)- 如果有人有更好的想法来显示此上下文中的上传进度,我愿意接受。

我必须将连续数据从一个 UIViewController 传输到另一个(如果可能的话)的唯一想法是使用 Singleton。我的代码在下面,我现在的问题是我不知道如何更新进度视图,即使现在它可以通过单例访问进度数据。

class SharedSingleton{

     private init(){}
     static let shared = SharedSingleton()
     var prog: Float = 0
}   

UITableViewController:

使用 Alamofire 获取上传完成的分数:

 /**TRACK PROGRESS OF UPLOAD**/
 upload.uploadProgress { progress in
 //print(progress.fractionCompleted)

 let mySingleton = SharedSingleton.shared
 mySingleton.prog = Float(progress.fractionCompleted)
 print("mySingleton.prog: \(mySingleton.prog)")

包含弹出窗口的 UIViewController:

@IBOutlet weak var popUpContainer: UIView!
@IBOutlet weak var uploadStatus: UILabel!
@IBOutlet weak var progressBar: UIProgressView!


override func viewDidLoad() {
    super.viewDidLoad()

    // Make popup have rounded corners
    popUpContainer.layer.cornerRadius = 5
    popUpContainer.layer.masksToBounds = true


    // Call Singleton and assign progress of upload to progress view
    // HOW TO UPDATE ??????
    let mySingleton = SharedSingleton.shared
    progressBar.progress = mySingleton.prog

}

一种选择是使用 NotificationCenter 并在您的弹出视图控制器中订阅通知,并在您的 API 进度回调中发布通知。

例如:

UploadNotifications.swift:

import Foundation

extension Notification.Name {
    static let UploadProgress = Notification.Name("UploadProgress")
}

UploadProgressViewController.swift(您的弹出窗口):

import UIKit

class UploadProgressViewController: UIViewController {

    @IBOutlet weak var progressBar: UIProgressView!

    private let progress: Progress = {
        let progress = Progress()
        progress.completedUnitCount = 0
        progress.totalUnitCount = 100
        return progress
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        NotificationCenter.default.addObserver(self, selector: #selector(self.uploadDidProgress(_:)), name: .UploadProgress, object: nil)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    @objc private func uploadDidProgress(_ notification: Notification) {
        if let progress = notification.object as? Int64 {
            self.progress.completedUnitCount = progress
            if progress == 100 {
                // dismiss/exit
            }
        }
    }

}

然后在你的上传进度回调方法中:

upload.uploadProgress { progress in
    NotificationCenter.default.post(name: .SyncDidProgress, object: Int64(progress))
}