gpt4 book ai didi

ios - 在 childByAutoId Firebase Swift 中访问特定数据

转载 作者:行者123 更新时间:2023-11-28 12:27:52 32 4
gpt4 key购买 nike

我想找到每个具有特定用户名的自动 ID 并更改该特定 AutoID 中的值。

每个具有我要查找的用户名的自动 ID。然后通过字符串更改与我指定的用户名匹配的所有自动 ID 的特定值。

因此每个具有用户名的 AutoID:“s7iytsdifytgsfyg”(示例)

然后更改所有这些 Auto ids photo_url 值。

enter image description here

enter image description here

//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"])
}
}

关于ios - 在 childByAutoId Firebase Swift 中访问特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42896998/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com