如何在Objective C中调用firebase快照而不是swift?


JSON
switch
uid
switch : true
uid2
switch : false

更新:以上是数据库结构,是我在Jay的评论后添加的。

在swift中,我会这样做:

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选择器

@objc func didLongPress() {
///that snapshot
}
override func awakeFromNib() {
super.awakeFromNib()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress))
like.addGestureRecognizer(longPress)
}

更新:可能的解决方案?

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

问题在于查询。下面是问题

的结构
JSON
switch
uid
switch : true
uid2
switch : false

,正在使用的查询正在查询以下

your_database
switch
uid
switch: true --> the query is running against this single child node <--
uid2
the query is NOT running here

如果您知道路径,就没有理由对单个子节点运行查询。如果目的是确定该子节点是否存在,则根本不需要查询。直接读取节点,看看它是否存在

let ref = your_database.child("switch").child(self.postID).child("switch")
ref.observeSingleEvent...

,如果switch以任何值(true或false)存在,它将在快照中返回。

编辑

如果您想知道子节点的值,如果它存在,它将在快照中。下面是一些代码

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

最新更新