Reputation: 301
I want to find every auto id with a specific Username and change values in that specific AutoID.
Every auto id that has the username that i am looking for. Then change a specific value on all auto IDs that matches my specified username by string.
So every AutoID that has Username: "s7iytsdifytgsfyg" (example)
Then change all those Auto ids photo_url value.
//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)
}
Upvotes: 0
Views: 814
Reputation: 6459
It's simple, you just need to find all keys containing the username
then update its value.
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)
})
Also I register the Notification
in viewDidLoad which tells me all data is retrieved from 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"])
}
}
Upvotes: 2