Firebase 2.0-无法从FIRDataSnapshot读取数据 [英] Firebase 2.0 - Reading data from FIRDataSnapshot not working

查看:42
本文介绍了Firebase 2.0-无法从FIRDataSnapshot读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iv有一个搜索栏,当您键入时,它会在数据库中搜索该用户的用户名.找到用户名的代码有效,但是当我尝试读取特定值时会崩溃.这是代码

Iv got a search bar that when you type it searches the database for that users username. The code that find the username work, but when i try and read a specific value it crashes. This is the code

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

          Database.child("users").queryOrderedByChild("username").queryEqualToValue(searchText).observeSingleEventOfType(.Value, withBlock: { snapshot in

        print(snapshot)
        print(snapshot.value!["first_name"] as? String)
        print(snapshot.value!["last_name"] as? String)
        print(snapshot.value!["username"] as? String)
        print(snapshot.value!["profile_picture_url"] as? String)
    })
}

打印快照的结果是

Snap (users) {
12345UIDEXample =     {
    "first_name" = Bob;
    "last_name" = Someone;
    "profile_picture_url" = "exampleurl.com";
    username = bobby;
  };
}

但是当我尝试访问时

snapshot.value!["first_name"] as? String

它返回nil并崩溃?为什么如果它在json中清楚地显示出它返回的数据已经存在但是却不允许我提取值呢?

it returns nil and crashes? Why if its clearly showing in the json that its returned that the data is there but wont let me exstract the value?

推荐答案

您的快照在子级的第一级上包含值"12345UIDEXample".

Your snapshot contains the value "12345UIDEXample" on the first level of children.

要访问您要查找的数据,可以使用循环遍历作为FIRDataSnapshot的子代.

To access the data you are looking for you can use a loop through the children casting as a FIRDataSnapshot.

for child in snapshot.children.allObjects as! [FIRDataSnapshot]{
    let firstname = child.value!["first_name"] as? String
}

在此示例中,子值将仅返回对象的另一个快照,如下所示:

In this example child value will only return another snapshot of your object like so:

Snap(12345UIDEXample) {
    "first_name" = Bob;
    "last_name" = Someone;
    "profile_picture_url" = "exampleurl.com";
    username = bobby;
};

但是,您将能够像以前尝试的那样访问所需的字段.

However you will be able to access the desired fields as you tried to previously.

这篇关于Firebase 2.0-无法从FIRDataSnapshot读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆