ios - 如何从 child 的 Firebase 获取数据?

标签 ios swift firebase firebase-realtime-database

我的数据结构是这样的:

structure

正常情况下应该有多个用户在里面,所以我在 channel ID里面得到了更多的 map 。我想从该 channel ID 中的第一个人那里检索用户 ID。当使用我的 channel ID 的正确路径时,我尝试了这个来检索用户 ID,首先遵循正常代码:

let firstChild = UInt(1)

     self.channelRef?.queryLimited(toFirst: firstChild).observeSingleEvent
(of: .value, with: { (snapshot) in
                            let value = snapshot.value as? NSDictionary

    })
    if let newCreator = snapshot.childSnapshot(forPath: "userID").value
                            {
                                print(newCreator)
                            }

    let newCreator = value?.["userID"] as! String

    let newCreator = value?["userID"] as? String ?? ""

    if snapshot.key == "userID"
                {
                    let newCreator = snapshot.value as! String
                }

没有任何效果,大部分输出只是零。这是快照打印,然后是值打印:

Snap (-KeLAUXw5juT1xBISOLA) {
    "-KeLCHhN3FPZ-chOE9MF" =     {
        PictureVersion = 2;
        readyToGo = 0;
        userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
        username = pietje;
    };
}
Optional({
    "-KeLCHhN3FPZ-chOE9MF" =     {
        PictureVersion = 2;
        readyToGo = 0;
        userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
        username = pietje;
    };
})

如何获取用户ID?

编辑:似乎我得到的唯一“ key ”是来自用户的随机 ID。我认为我需要从更深一层获取数据,但该怎么做?

最佳答案

let user = value.allValues.first! as! NSDictionary
let userID = user["userID"] as? String ?? ""

虽然当快照中没有用户时这会崩溃,所以请确保为此写一个检查。这样做可能会更好。

self.channelRef?.queryLimited(toFirst: firstChild).observeSingleEvent(of: .value, with: { snapshot in
    let enumerator = snapshot.children
    while let user = enumerator.nextObject() as? FIRDataSnapshot {
        guard let userValue = user.value as? NSDictionary else {
            return
        }
        let userID = userValue["userID"] as? String ?? ""
    }
})

关于ios - 如何从 child 的 Firebase 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42589261/

相关文章:

c# - 将 InputAccessoryView 设置为 UISearchController

ios - 使用 AngularJS 在 PhoneGap 3.3 for iOS 中登录 XCODE

swift - 代码清理 Swift

ios - 想在谷歌日历中添加事件

database - 我可以在 Cloud Firestore 中将集合设置为仅追加吗?

firebase - 如何只允许一个管理员用户编写 Firebase 数据库?

ios - 手势识别器 :shouldBeRequiredToFailByGestureRecognizer crashing

ios - ARKit - SceneView 显示错误位置 3D 模型

ios - 如何使 Xcode 8.2.1 显示导致异常的行?

android - Ionic View Google 登录弹出窗口在 Firebase 2 中有效,但在 Firebase 3 中无效(在浏览器中有效)