如何使用查询按值获取json对象。在详细信息中,想要获取id {4的1而不循环json表中的所有事件
答案 0 :(得分:3)
Swift 2
FIRDatabase.database().reference().child("events").queryOrderedByChild("id").queryEqualToValue(4).observeSingleEventOfType(.Value, withBlock: {(Snap) in
if let snapDict = Snap.value as? [String:AnyObject]{
for each in snapDict{
print(each.0) // Will print out your node ID = 1
print(each.1) //Will print out your Dictionary inside that node.
}
}
})
Swift 3
FIRDatabase.database().reference().child("events").queryOrdered(byChild: "id").queryEqual(toValue: 4).observeSingleEvent(of: .value, with: {(Snap) in
if let snapDict = Snap.value as? [String:AnyObject]{
for each in snapDict{
print(each.0) // Will print out your node ID = 1
print(each.1) //Will print out your Dictionary inside that node.
}
}
})
答案 1 :(得分:1)
可能会解决您的问题
[self.dbRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
if (![snapshot.value isKindOfClass:[NSNull class]]) {
NSArray *arrResponse = (NSArray *)snapshot.value;
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", serchID];
NSArray *arrSearchedVal = [arrResponse filteredArrayUsingPredicate:pred];
}
}];
NB: dbRef是您的FIRDatabaseReference,它返回整个数据JSON。然后将NSPredicate与您的搜索ID一起使用,您将获得结果。
快乐编码..