![](/img/trans.png)
[英]Retrieving specific Firebase data that is stored in a childByAutoId() Reference (Swift)
[英]Access specific data in childByAutoId Firebase Swift
我想找到每个具有特定用户名的自动ID,并更改该特定AutoID中的值。
每个具有我要查找的用户名的自动ID。 然后,按字符串更改与我指定的用户名匹配的所有自动ID的特定值。
因此,每个具有用户名的自动ID:“ s7iytsdifytgsfyg”(示例)
然后更改所有这些自动ID的photo_url值。
//configureAuth()
NotificationCenter.default.addObserver(self, selector: #selector(updateValue(_ :)), name: Notification.Name("TIME_TO_UPDATE"), object: nil)
func updateValue(_ notification: Notification) {
//Firebase Initialization
var ref: FIRDatabaseReference!
//var storage: FIRStorageReference!
let userID = FIRAuth.auth()?.currentUser?.uid
ref = FIRDatabase.database().reference()
//storage = FIRStorage.storage().reference()
//Get Data from database resend to database
ref.child("Users").child(userID!).observeSingleEvent(of: .value, with: {(snapshot) in
let snapDict = snapshot.value as? NSDictionary
let firebaseUserPhotoURL = snapDict?["photo_url"] as? String ?? ""
for key in self.keys {
self.ref.child("general_room").child(key).updateChildValues(["photo_rul": firebaseUserPhotoURL])
}
})
}
func changeChatPhoto() {
//Firebase Initialization
var ref: FIRDatabaseReference!
let userID = FIRAuth.auth()?.currentUser?.uid
ref = FIRDatabase.database().reference()
let observer = ref.child("general_room").observe(.value, with: { (snapshot) in
let messages = snapshot.value as? [String: Dictionary<String, String>]
for (key, value) in messages! {
if value["user_name"] == userID { // Field you want to find
self.keys.append(key) // keep track of the key (auto id)
}
}
NotificationCenter.default.post(name: Notification.Name("TIME_TO_UPDATE"), object: nil)
})
// Just observe for one time
ref.child("general_room").removeObserver(withHandle: observer)
}
很简单,您只需要查找包含username
所有键,然后更新其值即可。
ref.child("general_room").observeSingleEvent(of: .value, with: { (snapshot) in
let general_room = snapshot.value as! [String: Dictionary<String, String>]
for (key, value) in general_room {
if value["user_name"] == "HELLO WORLD" { // Field you want to find
self.keys.append(key) // keep track of the key (auto id)
}
}
NotificationCenter.default.post(name: Notification.Name("TIME_TO_UPDATE"), object: nil)
})
另外,我在viewDidLoad中注册了Notification
,它告诉我所有数据都是从firebase检索到的。
var keys = [String]()
override func viewDidLoad() {
...
NotificationCenter.default.addObserver(self, selector: #selector(updateValue(_ :)), name: Notification.Name("TIME_TO_UPDATE"), object: nil)
}
func updateValue(_ notification: Notification) {
for key in keys {
self.ref.child("general_room").child(key).updateChildValues(["photo_rul": "http://google.com"])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.