您如何在Objective C中而不是Swift调用Firebase快照? [英] How do you call a firebase snapshot in Objective C instead of swift?
问题描述
JSON
switch
uid
switch : true
uid2
switch : false
更新:上面是数据库结构,我在Jay评论后添加了它.
Update: above is the database structure, which I added after Jay's comment.
我会尽快:
let databaseRef = Database.database().reference().child("switch").child(self.postID)
databaseRef.queryOrdered(byChild: "switch").queryEqual(toValue: "true").observeSingleEvent(of: .value) { (snapshot) in
print(snapshot)
if snapshot.exists() {
print("Address is in DB")
} else {
print("Address doesn't exist")
}
}
但是我必须使用Objective C,因为必须使用Objective C选择器
But I have to use Objective C because I have to use an Objective C selector
@objc func didLongPress() {
///that snapshot
}
override func awakeFromNib() {
super.awakeFromNib()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress))
like.addGestureRecognizer(longPress)
}
更新:可能的解决方案?
Update: Possible solution?
let ref = Database.database().reference().child("switch").child(self.postID).child("switch")
ref.observeSingleEvent(of:.value, with: {snapshot in
if snapshot.exists() {
print("Got data \(snapshot.value!)") //will print true or false
let ab = snapshot.value!
if ab as! Int>0 {
print("yes")
} else {
print("no")
}
}
else {
print("No data available")
}
})
推荐答案
问题出在查询中.这是问题的结构
The issue is with the query. Here's the structure from the question
JSON
switch
uid
switch : true
uid2
switch : false
正在使用的查询正在查询以下
and the query being used is querying the following
your_database
switch
uid
switch: true --> the query is running against this single child node <--
uid2
the query is NOT running here
如果您知道路径,则实际上没有理由针对单个子节点运行查询.如果目的是确定该子代是否存在,则根本不需要查询.只需直接读取该节点,看看它是否存在
There's really no reason to run a query against a single child node if you know the path. If the purpose is to determine if that child exists, there's no need for query at all. Just read the node directly and see if it exists
let ref = your_database.child("switch").child(self.postID).child("switch")
ref.observeSingleEvent...
并且如果存在带有任何值(true或false)的switch,它将在快照中返回.
and if switch is present with any value (true or false) it will be returned in the snapshot.
编辑
如果您想知道子项的值,则该子项将存在于快照中(如果存在).这是一些代码
If you want to know the value of the child, it will be in the snapshot if it exists. Here's some code
let ref = your_database.child("switch").child(self.postID).child("switch")
ref.getData { (error, snapshot) in
if let error = error {
print("Error getting data \(error)")
}
else if snapshot.exists() {
let myBool = snapshot.value as? Bool ?? false
print("Got data \(myBool)") //will print true or false
}
else {
print("No data available")
}
}
这篇关于您如何在Objective C中而不是Swift调用Firebase快照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!