使用Firebase Swift检索数据 [英] Retrieving Data using Firebase Swift

查看:100
本文介绍了使用Firebase Swift检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的Swift iOS应用程序使用Firebase。我发现在Firebase的指南检索数据教程有点混乱,我不知道为什么当我尝试访问我的数据库中的现有值结果零值。



这是到目前为止:

  usersRef.queryOrderedByChild(fbid)。q​​ueryEqualToValue(userId).observeSingleEventOfType(.Value,withBlock :{快照在
print(SNAPSHOT:,snapshot.value)

打印快照的结果。

  SNAPSHOT:{
1 = {
fbid = 1;
firstName = Michelle;
friendlist = {
9 =Kevin C;
};
lastName = C;
profilepicurl =https :;
uid =脸书:1;
};
}

但是,下面的结果是:

致命错误:意外地发现零,而解包可选值

 科幻rstName = snapshot.value.objectForKey(firstName)as!字符串

我想检索用户的所有值(firstName,profilepicurl,friendlist等)并将它们存储在变量中。这似乎很简单,但也许我错过了一些东西。任何帮助,将不胜感激。 FDataSnapshot 不包含小孩 >的firstName 。它只包含一个小孩 1

这是因为你正在执行一个查询,然后询问一个值。由于一个查询可以有很多结果,它返回一个结果列表。即使只有一个结果,它仍然是一个1的列表。



解决方案是循环的孩子:



pre $ usersRef.queryOrderedByChild(fbid)
.queryEqualToValue(userId)
.observeSingleEventOfType(.Value,withBlock:{snapshot in
for child在snapshot.children {
print(Loading group \(child.key!))
}
})


I'm using Firebase for my Swift iOS application. I found the retrieving data tutorial on Firebase's guide a bit confusing and I am not sure why when I try to access existing values in my database results in nil values.

This is what I have so far:

usersRef.queryOrderedByChild("fbid").queryEqualToValue(userId).observeSingleEventOfType(.Value, withBlock:{ snapshot in
                        print("SNAPSHOT: ",snapshot.value)

Here is the result of printing snapshot.

SNAPSHOT:  {
    1 = {
        fbid = 1;
        firstName = Michelle;
        friendlist =         {
            9 = "Kevin C";
        };
        lastName = C;
        profilepicurl = "https:;
        uid = "facebook:1";
    };
}

However, the line below results in:
fatal error: unexpectedly found nil while unwrapping an Optional value

 firstName = snapshot.value.objectForKey("firstName") as! String

I would like to retrieve all the values for the user (firstName, profilepicurl, friendlist, etc) and store them in variables. It seems simple but perhaps I'm missing something. Any help would be appreciated.

解决方案

Your FDataSnapshot does not contain a child firstName. It only contains a child 1.

This is because you're performing a query and then asking for a value. Since a query can have many results, it returns a list of results. Even when there's only one result, it is still a list of 1.

The solution is to loop over the children:

usersRef.queryOrderedByChild("fbid")
        .queryEqualToValue(userId)
        .observeSingleEventOfType(.Value, withBlock:{ snapshot in
            for child in snapshot.children {
                print("Loading group \(child.key!)") 
            }
})

这篇关于使用Firebase Swift检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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