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

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

问题描述

我将 Firebase 用于我的 Swift iOS 应用程序.我发现 Firebase 指南上的检索数据教程有点令人困惑,我不确定为什么当我尝试访问数据库中的现有值时会导致值为零.

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.

这是我目前所拥有的:

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

这是打印快照的结果.

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

但是,下面的行会导致:
致命错误:解包可选值时意外发现 nil

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

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

我想检索用户的所有值(firstName、profilepicurl、friendlist 等)并将它们存储在变量中.这看起来很简单,但也许我错过了一些东西.任何帮助,将不胜感激.

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.

推荐答案

您的 FDataSnapshot 不包含子 firstName.它只包含一个子1.

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

这是因为您正在执行查询然后请求一个值.由于查询可以有很多结果,因此它返回一个结果列表.即使只有一个结果,它仍然是一个 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.

解决方案是遍历孩子:

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天全站免登陆