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

时间:2018-05-05 12:03:01

标签: ios swift alamofire progress uiprogressview

我有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

}

enter image description here

1 个答案:

答案 0 :(得分:2)

一种选择是使用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))
}