我正在使用Firebase,直到最近我才按字母顺序获取数据.我从不使用查询,我总是只使用数据快照并逐个排序.最近,数据并不总是按照snapVal的字母顺序排列.我怎么做到这一点,我得到一个按字母顺序排序的snapVal数据,就像它在数据库的快照中一样?
真实示例:有4条消息,id1-id4(按此顺序).他们传达了消息"1" - "4".快照看起来正确.但是snapVal(snapshot.value)看起来像这样:
["id2": {
DATE = "10/20/16";
"FIRST_NAME" = first;
ID = userID;
"LAST_NAME" = last;
MESSAGE = 2;
TIME = "8:12 PM";
}, "id4": {
DATE = "10/20/16";
"FIRST_NAME" = first;
ID = userID;
"LAST_NAME" = last;
MESSAGE = 4;
TIME = "8:12 PM";
}, "id1": {
DATE = "10/20/16";
"FIRST_NAME" = first;
ID = userID;
"LAST_NAME" = last;
MESSAGE = 1;
TIME = "8:12 PM";
}, "id3": {
DATE = "10/20/16";
"FIRST_NAME" …Run Code Online (Sandbox Code Playgroud) 我有一个查询,根据用户ID搜索用户.
usersRef.queryOrderedByChild("email").queryEqualToValue(email).observeEventType(.Value, withBlock: { snapshot in
if snapshot.exists() {
print("user exists")
print(snapshot.key)
Run Code Online (Sandbox Code Playgroud)
查询返回正确的用户,但该行print(snapshot.key)字面上返回单词"users",而不是实际的用户ID.print(snapshot)返回以下用户:
Snap (users) {
DELyncz9ZmTtBIKfbNYXtbhUADD2 = {
email = "test3@gmail.com";
"first_name" = test;
"last_name" = test;
};
Run Code Online (Sandbox Code Playgroud)
我该怎么DELyncz9ZmTtBIKfbNYXtbhUADD2办?我可以通过使用来获取电子邮件,let email = child.value["email"]但我无法获取密钥,因为它不是命名属性.
谢谢!!
编辑:感谢Frank的回答更新了代码.入门ambiguous use of key
query.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.key)
if snapshot.exists() {
print("user exists")
for child in snapshot.children {
print(child.key)
Run Code Online (Sandbox Code Playgroud) 我的数据库结构是这样的:
{
"users": {
"alovelace": {
"name": "Ada Lovelace",
"score": 4,
},
"ghopper": { ... },
"eclarke": { ... }
}
}
Run Code Online (Sandbox Code Playgroud)
我试图按降序检索前20个分数.
let queryRef = FIRDatabase.database().reference().child("users").queryOrderedByChild("score").queryLimitedToLast(20)
queryRef.observeSingleEventOfType(.Value, withBlock: { (querySnapShot) in
print(querySnapShot.value)
})
Run Code Online (Sandbox Code Playgroud)
我想要输出像
score": 4
score": 3
score": 2
or
score": 2
score": 3
score": 4
or
2
3
4
Run Code Online (Sandbox Code Playgroud)
请让我知道如何解决这个问题.