我按照firebase中的说明操作,但即使确保文本条目为String类型,我仍然会崩溃。
这是错误:
由于未捕获的异常'InvalidPathValidation'而终止应用,原因:'(child :)必须是非空字符串且不包含'。' '#''$''['或']''
这是代码:
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAuth
class BioEditViewController: UIViewController {
@IBOutlet weak var bioTextView: UITextView!
let databaseRef = FIRDatabase.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
let userID = FIRAuth.auth()?.currentUser?.uid
databaseRef.child("users").child(userID!).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// Get user level
let userBio = snapshot.value!["userBio"] as! String
self.bioTextView.text = userBio
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doneSave(sender: UIButton) {
let textView = bioTextView.text
self.dismissViewControllerAnimated(false, completion: nil)
databaseRef.child("users/(user.uid)/userBio").setValue(textView)
}
}
我只是想更新一个特定的子节点:userBio而不影响整个对象。
答案 0 :(得分:5)
警告强>
避免将数据库引用实例化为超出范围的变量。原因: - 在您的范围之外,当您将类实例化为变量时,您不知道 FIRApp
是否已经配置,或者通常是否已经配置甚至已经初步确定了。只需为变量提供一个引用(!),然后在范围内实例化。
更改: -
let databaseRef = FIRDatabase.database().reference()
到
let databaseRef = FIRDatabaseReference!
在使用它之前,只需将其初始化为: -
databaseRef = FIRDatabase.database().reference()
尝试: -
@IBAction func doneSave(sender: UIButton) {
let textView = bioTextView.text
self.dismissViewControllerAnimated(false, completion: nil)
databaseRef = FIRDatabase.database().reference()
databaseRef.child("users/\(FIRAuth.auth!.currentUser!.uid)/userBio").setValue(textView)
}