iOS swift : best way to pass data to other VCs after query is completed

标签 ios swift firebase firebase-realtime-database swift3

上下文:使用由 Firebase 3.0 提供支持的 Swift 3 编写的 iOS 应用

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

应用架构概述:

ProfileVC - where I fetch the currentUser's data from Firebase & display the currentScore.

⎿ 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),但这不起作用,因为它在ProfileVC上的查询完成之前传递了“nil”。

我想避免使用全局变量,因为有人告诉我这是不好的做法。

任何想法将不胜感激。

最佳答案

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

所以在 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 中提取所有信息... 然后可以按照与上面相同的方式对信息进行排序。

关于iOS swift : best way to pass data to other VCs after query is completed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40703542/

相关文章:

ios 以离线模式存储 URL 图像(未连接到互联网)

ios - 滚动 ViewController Swift

ios - 在 Firebase 身份验证中更新电话号码 - Swift

ios - (iOS) 音乐文件停止时的操作

java - 即使数据相同,Firebase 中也会存储不同类型的数据

ios - 界面生成器中的图像和标签与 TableView 单元格中的数据重叠

ios - 为什么我不能在模拟器中点击 uibutton,但可以在我的硬件 iPhone 上点击 uibutton?

ios - UITableViewController 布局不起作用

ios - 默认上下文为零!你忘记初始化核心数据栈了吗? [魔法唱片]

ios - 在 guard 语句 swift 中呈现一个 ViewController