iOS Swift:查询完成后将数据传递给其他VC的最佳方式

时间:2016-11-20 11:36:06

标签: ios swift firebase firebase-realtime-database swift3

上下文:使用Firebase 3.0支持的Swift 3中编写的iOS应用程序

挑战:在我的应用中,用户的 currentScore 存储在Firebase中。此用户可以从多个ViewControllers完成/取消完成任务(这将增加/减少其 currentScore )。

应用程序架构概述:

  

ProfileVC - 我从Firebase&获取当前用户的数据。显示当前的分数。

     

⎿ContainerView

  ⎿ CollectionViewController - users can update their score from here

     ⎿ DetailsVC - (when users tap on a collectionView cell) - again users can update their score from here.

enter image description here

问题:我需要将currentScore传递给可以更新分数的VC。我想过在级联中使用prepare(forSegue),但这并没有起作用,因为它通过" nil"在ProfileVC上的查询完成之前。

我想避免使用全局变量,因为我被告知这是一个不好的做法。

任何想法都会非常感激。

2 个答案:

答案 0 :(得分:0)

尝试实例化,首先将导航控制器嵌入到您的第一个故事板中,然后将 storyboardID 提供给您要显示的VC。

 let feedVCScene = self.navigationController?.storyboard?.instantiateViewController(withIdentifier: "ViewControllerVC_ID") as! ViewController

 feedVCScene.scoreToChange = current_Score //  scoreToChange is your local variable in the class

                                           //  current_Score is the current score of the user.

 self.navigationController?.pushViewController(feedVCScene, animated: true)

PS: - 实例化比模态segue故事板传输更健康的原因,它几乎消除了你来回导航时的内存泄漏,避免堆积VC。

答案 1 :(得分:0)

为什么不创建一个在执行任何其他操作之前提取所有数据的函数。

所以在ViewDidLoad中调用...

pullFirebaseDataASYNC()

功能如下所示......

typealias CompletionHandler = (_ success: Bool) -> Void

func pullFirebaseDataASYNC() {

    self.pullFirebaseDataFunction() { (success) -> Void in
        if success {

            // Perform all other functions and carry on as normal...

Firebase功能可能看起来像......

    func pullFirebaseDataFunction(completionHandler: @escaping CompletionHandler) {

    let refUserData = DBProvider.instance.userDataRef
    refUserData.observeSingleEvent(of: .value, with: { snapshot in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            self.userCurrentScore = dictionary["UserScore"] as! Int
            completionHandler(true)
        }
    })
}

然后当你跨越信息时... 在ProfileVC中 创建2个属性

var containerVC: ContainerVC!
var userCurrentScore = Int()

在ProfileVC中包含以下功能......

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ProfileToContainerSegue" {
        let destination = segue.destination as! ContainerVC
        containerVC = destination

        containerVC.userCurrentScore = userCurrentScore
      }
    }

在ContainerVC中创建一个属性

    var userCurrentScore = Int()

改进方法可能是一条错误消息,以确保在用户可以继续之前从Firebase中提取所有信息... 然后可以通过与上面相同的方式来处理信息。