ios - 从 Firebase 检索子值

标签 ios swift firebase

我有一个查找特定 UUID 并返回对象的查询。

print(snapshot)  
Snap (users) {
"-KENROf9kGUPw1j6ghFo" =     {
    UUID = "A1166D66-31B4-4B1C-B28C-58E9E5615D16";
    nickname = Craig;
};
}

我正在尝试提取 nickname但有麻烦。

这是我的查询 let queryRef = Firebase(url:"https://<url>.firebaseio.com/users")

这是查询引用。

var handle = queryRef.queryOrderedByChild("UUID").queryEqualToValue("A1166D66-31B4-4B1C-B28C-58E9E5615D16").observeSingleEventOfType(.Value, withBlock: { snapshot in
        if snapshot.value is NSNull {
            print("snapshot empty")
        } else {
            print(snapshot) //this prints the snapshot above
            self.nickname = snapshot.value.objectForKey("nickname") as! String  //this returns an error
            print(self.nickname)
        }
    })
}

self.nickname....行返回以下错误。

fatal error: unexpectedly found nil while unwrapping an Optional value我已经尝试了几种不同的方法来构建它,但还没有找到一种不会失败的方法。

最佳答案

您将用户存储在推送 ID 下,然后通过用户的 UID 查询他们。这是个坏主意。相反,将用户存储在其 uid(或在您的情况下为 UUID)下,如 Firebase documentation on storing user data 中的示例所示。显示:

ref.authUser("jenny@example.com", password:"correcthorsebatterystaple") {
    error, authData in
    if error != nil {
        // Something went wrong. :(
    } else {
        // Authentication just completed successfully :)
        // The logged in user's unique identifier
        println(authData.uid)
        // Create a new user dictionary accessing the user's info
        // provided by the authData parameter
        let newUser = [
            "provider": authData.provider,
            "displayName": authData.providerData["displayName"] as? NSString as? String
        ]
        // Create a child path with a key set to the uid underneath the "users" node
        // This creates a URL path like the following:
        //  - https://<YOUR-FIREBASE-APP>.firebaseio.com/users/<uid>
        ref.childByAppendingPath("users")
           .childByAppendingPath(authData.uid).setValue(newUser)
    }
}

如果您坚持使用当前的数据结构,则需要处理 .Value 查询返回子级列表的事实。即使只有一项符合查询条件,它仍然是一项的列表。

var query = queryRef.queryOrderedByChild("UUID").queryEqualToValue("A1166D66-31B4-4B1C-B28C-58E9E5615D16")
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
    if snapshot.value is NSNull {
       print("snapshot empty")
    } else {
        for child in snapshot.children {
            self.nickname = child.value.objectForKey("nickname") as! String
            print(self.nickname)
        }
    }
})

关于ios - 从 Firebase 检索子值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389880/

相关文章:

android - AWS DynamoDB 扫描在 iOS 上失败但在 Android 上运行

ios - 将 PDF 转换为 UIImage

swift - 如何在 Swift 中将字符串 "\u{0026}"转换为 "&"?

firebase - 前端 Firebase 请求在通过公司代理加载的网站上被阻止

Swift Firebase 按子级的子级查询

ios - UIButton.isSelected 不能 Observable

ios - 如何制作像 propellerhead 的应用程序 "Figure"这样的自定义 Controller ?

ios - OpenGL ES 2.0 (iOS) 中的二维绘图

Swift TableView 单元格不显示

android - Google Analytics 不生成配置文件,Firebase 冲突