Firebase snapshot.key没有返回实际密钥?

时间:2016-06-02 01:19:07

标签: swift firebase swift2 firebase-realtime-database

我有一个基于用户ID搜索用户的查询。

usersRef.queryOrderedByChild("email").queryEqualToValue(email).observeEventType(.Value, withBlock: { snapshot in
    if snapshot.exists() {
        print("user exists")
        print(snapshot.key)

查询返回正确的用户,但行print(snapshot.key)字面上返回单词“users”,而不是实际的用户ID。 print(snapshot)返回以下用户:

Snap (users) {
   DELyncz9ZmTtBIKfbNYXtbhUADD2 =     {
       email = "test3@gmail.com";
       "first_name" = test;
       "last_name" = test;
   };

我如何获得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)

1 个答案:

答案 0 :(得分:5)

在某个位置运行查询时,结果将是匹配子项的列表。即使只有一个匹配项,结果也会是一个孩子的列表。

您正在打印所有结果孩子的钥匙。由于没有单一结果,SDK会打印您查询的位置/集合的密钥:users

您可能正在寻找的是循环匹配的孩子并打印他们的钥匙:

let query = usersRef.queryOrderedByChild("email").queryEqualToValue(email)
query.observeEventType(.Value, withBlock: { snapshot in
    for child in snapshot.children {
        print(child.key)
    }
})