上下文:使用由 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.
问题:我需要将 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/