首页 文章

(Swift)如果我的节点是自定义索引,如何查询当前用户的实时数据快照?

提问于
浏览
0

对不起,如果 Headers 有点罗嗦:P我正在使用Swift和Firebase .

我在Firebase上设置了一条规则来将我的用户数据库编入“Username”的索引,但当我在代码中查询当前用户数据的快照时,它总是返回nil ...我猜是因为我只能纯粹通过他们的uid识别当前用户?

这是我的示例JSON树:

enter image description here

如上所示,在Firebase中,我根据用户在我的应用中创建的“用户名”索引了我的用户数据 . 但是,当我想检索用户的其他子节点的值时,我甚至无法访问用户的数据树,因为就应用程序的启动而言,它不知道当前用户的“用户名” “......它只能无限期地知道当前用户的uid .

What I want to do:

我想使用 let user : String = (Auth.auth().currentUser?.uid)! 并在我的数据库中搜索与 user 匹配的子节点值,然后我想获得该用户数据的快照...从 Headers “ User1 ”开始并包括它的所有子节点 .

请帮助我正确的程序来做到这一点,我迷路了:P谢谢!

1 回答

  • 0

    这就是我最终做的事情 . 我并不认为它是最好的方法,但它可以工作并清楚地显示如何从Firebase中的密钥中检索子值:

    下面的所有代码都在常规自定义功能(未显示)内 .

    if Auth.auth().currentUser != nil { //Makes sure that there is a user currently registered/logged in
    
        let ref = Database.database().reference() //Gets a reference to my database
    
        //Dives into the 'Users' node, then into the user's specific data node based on their username (gathered from device's 'User Defaults')
        ref.child("Users").child(username).observeSingleEvent(of: .value, with: { (snapshot) in
    
            let value = snapshot.value as? NSDictionary //Gets a snapshot of all the data specific to the current user
            let usersEmail = value?.value(forKeyPath: "Email") //Gets the value of the specified key in the snapshot
    
            print(usersEmail!)
    
            })
        }
    

    打印“ a@b.com ". Since I'm indexing my Firebase database by each user's "用户名”作为包含数据子节点的主节点(而不是用户的 uid 作为主节点),我需要保存用户's username as a string in their device'的用户默认值,以便在识别当前用户的数据时可以调用该值由他们的"Username"特定节点 .

    请注意,这仅适用于您的应用在用户创建用户名时支持测试唯一用户名的情况 .

相关问题