【问题标题】:Update Value Firebase Swift 3更新值 Firebase Swift 3
【发布时间】:2017-08-05 13:04:02
【问题描述】:
我在使用键 status 更新 Firebase 数据库中的值时遇到问题。我只是不知道如何访问它是 autoID 的 child(id)。我应该在我的 Swift 3 实体中有一个属性吗?还是有一个孩子(autoID)或类似的东西?我是 Firebase 和 Swift 3 的新手。有人可以帮忙吗?这是我的代码:
self.ref?.child("requests").queryOrdered(byChild: "Sender").queryEqual(toValue: self.items[indexPath.row].Sender).setValue("2", forKey: "status"))
【问题讨论】:
标签:
ios
swift
firebase
swift3
firebase-realtime-database
【解决方案1】:
您可以如下更新状态值:
self.ref?.child("requests").queryOrdered(byChild: "Sender").queryEqual(toValue: self.items[indexPath.row].Sender).observe(.value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
if value != nil {
self.ref.child("requests/(self.items[indexPath.row].Sender)").updateChildValues(["status":"2"])
}
})
【解决方案2】:
Swift 3 && Firebase 3
希望此代码对您有所帮助...
// create the reference you want to observe
let myRequestRef = FIRDatabase.database().reference().child("requests").queryOrdered(byChild: "Sender").queryEqual(toValue: self.items[indexPath.row].Sender)
// check the sender value
myRequestRef.observeSingleEvent(of: .value, with: { (snapshot) in
//get the sender key
let senderKey = snapshot.key as String
// create status ref for new status value
let statusRef = FIRDatabase.database().reference().child("requests").child(senderKey)
// create new dict for status value
let newValue = ["Status": 2] as [String: Any]
statusRef.updateChildValues(newValue, withCompletionBlock: { (error, _) in
if error != nil {
print(error?.localizedDescription ?? "Failed to set status value")
}
print("Successfully set status value")
// Update your UI
DispatchQueue.main.async {
// Do anything with your UI
}
})
}) { (error) in
print("Failed to get snapshot", error)
}
【解决方案3】:
尝试将您的代码移入.observe。这将允许您获取状态并检查它是否正在访问正确的孩子。通过使用下面的子路径,它将覆盖 status 值,但不会覆盖子路径中的其余值。
self.ref?.child("requests").queryOrdered(byChild: "Sender").queryEqual(toValue: self.items[indexPath.row].Sender).observe(.value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
if value != nil {
print(value)
print(value["status"])
// If status is what you want, and prints out the correct status and
// correct child item
// Update the status
self.ref.child("requests/\(self.items[indexPath.row].Sender)/status").setValue("2")
}
})
我还没有测试上面的代码,但是你应该可以做一些小的调整,让它在你的代码和你的 firebase 数据库中工作。