使用Firebase和Swift从未知的子名称中检索数据 [英] Retrieve data from an unknown child name with Firebase and Swift

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

问题描述

我将Firebase用作IOS应用程序的数据库.我想从数据库中检索几个用户的数据.

I'm using Firebase as the database for my IOS app. I want to retrieve data of several users from the database.

这是我的数据库组织:

  • 用户

  • UserID1
    • 位置:value1
    • 位置:Value2

    ...

    我想检索数据库所有用户的位置数据.

    I want to retrieve the location data of all the users of the database.

    基本快照功能

        ref.child("Users").child("").child("Location").observe(.value, with: {
            snapshot in
    
            for Location in snapshot.children {
                self.locationsArray.append((Location as AnyObject).key)
            }
            print(self.locationsArray)
        })
    

    我的问题是:即使我未指定(我无法指定)作为孩子名字的userID,如何获取所有 Locations 前?谢谢.

    My question is: how can I retrieve all the Locations even if I don't specify (I can't) the userID that is the name of a child before? Thanks.

    推荐答案

    下面是一个代码段,该代码段检索并打印每个用户的uid及其位置.

    Here's a code snippet that retrieves and prints the uid of each user and their location.

    我们可以使用.query进一步完善结果

    We can further refine our results with a .query

    let usersRef = ref.child("users")
    usersRef.observeSingleEvent(of: .value, with: { (snapshot) in
    
        for snap in snapshot.children {
            let userSnap = snap as! FIRDataSnapshot
            let uid = userSnap.key //the uid of each user
            let userDict = userSnap.value as! [String:AnyObject] //child data
            let location = userDict["Location"] as! String
            print("key = \(uid) is at location = \(location)")
        } 
    })
    

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

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