【发布时间】:2016-08-08 02:24:07
【问题描述】:
在我的 iOS 应用程序中,我有两个与 Firebase 相关的函数,我想在 viewDidLoad() 中调用它们。第一个选择一个带有.queryOrderedByKey() 的随机孩子并将孩子的密钥作为字符串输出。第二个使用该键和observeEventType 检索子值并将其存储在字典中。当我使用 UI 中的按钮触发这些功能时,它们会按预期工作。
但是,当我将这两个函数都放在 viewDidLoad() 中时,我得到了这个错误:
由于未捕获的异常“InvalidPathValidation”而终止应用程序,原因:“(子:)必须是非空字符串且不包含“。” '#' '$' '[' 或 ']''
有问题的代码行在我的 AppDelegate.swift 中,以红色突出显示:
class AppDelegate: UIResponder, UIApplicationDelegate, UITextFieldDelegate
当我注释掉第二个函数并将第一个函数留在 viewDidLoad 中时,应用程序加载正常,随后对两个函数的调用(由按钮操作触发)按预期工作。
我在第一个函数的末尾添加了一行打印出 URL 字符串,它没有任何违规字符:https://mydomain.firebaseio.com/myStuff/-KO_iaQNa-bIZpqe5xlg
我还在 viewDidLoad 中的函数之间添加了一条线来对字符串进行硬编码,但我遇到了同样的 InvalidPathException 问题。
这是我的 viewDidLoad() 函数:
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
pickRandomChild()
getChildValues()
}
这是第一个函数:
func pickRandomChild () -> String {
var movieCount = 0
movieRef.queryOrderedByKey().observeEventType(.Value, withBlock: { (snapshot) in
for movie in snapshot.children {
let movies = movie as! FIRDataSnapshot
movieCount = Int(movies.childrenCount)
movieIDArray.append(movies.key)
}
repeat {
randomIndex = Int(arc4random_uniform(UInt32(movieCount)))
} while excludeIndex.contains(randomIndex)
movieToGuess = movieIDArray[randomIndex]
excludeIndex.append(randomIndex)
if excludeIndex.count == movieIDArray.count {
excludeIndex = [Int]()
}
let arrayLength = movieIDArray.count
})
return movieToGuess
}
这是第二个功能:
func getChildValues() -> [String : AnyObject] {
let movieToGuessRef = movieRef.ref.child(movieToGuess)
movieToGuessRef.observeEventType(.Value, withBlock: { (snapshot) in
movieDict = snapshot.value as! [String : AnyObject]
var plot = movieDict["plot"] as! String
self.moviePlot.text = plot
movieValue = movieDict["points"] as! Int
})
return movieDict
)
为了更好地衡量,这是我的 AppDelegate.swift 的相关部分:
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITextFieldDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
return true
}
我猜 Swift 执行的代码不是我期望的顺序。 Swift 在运行第二个函数之前不会自动等待第一个函数完成吗?如果是这样,为什么这种配对在应用程序的其他地方有效,但在 viewDidLoad 中无效?
【问题讨论】:
标签: ios swift firebase firebase-realtime-database