我想在名为“users”的孩子中更新名为“PhotoGallery”的子值。
如何重写此代码。
func registerDatabase(id: String, url: [String: AnyObject]) {
//Create a database reference
let userRef = self.databaseRef.child("users").childByAutoId().child(id)
userRef.updateChildValues(["PhotoGallery":url]) {(error, ref) in
if error != nil{
print("Error registering Firebase database: \(error)")
return
}
print("Successfully stored in DB")
}
}
func removeSpecialCharsFromString(text: String) -> String {
let validChars: Set<Character> = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".characters)
return String(text.characters.filter{validChars.contains($0)})
}
答案 0 :(得分:1)
setValue将执行此操作,因为您正在使用childByAutoId动态创建子节点。
let userChildRef = self.databaseRef.child("users").childByAutoId()
let photoRef = userChildRef.child("id").child("PhotoGallery")
photoRef.setValue(url)
结果
users
-Yuhusn9asijasd
id
PhotoGallery: "www.someurl.com"
注意我将photoRef作为单独的let使其更具可读性,因为userChildRef现在引用该用户的所有子项
let nameRef = userChildRef.child("name")
nameRef.setValue("Gilligan")
let hatColorRef = userChildRef.child("hat")
hatColorRef.setValue("White")
let shirtColorRef = userChildRef.child("shirt")
shirtColorRef.setValue("Red")
users
-Yuhusn9asijasd
id:
PhotoGallery: "www.someurl.com"
name: "Gilligan"
hat: "White"
shirt: "Red"