【问题标题】:Fetch User Info and append to an Array获取用户信息并附加到数组
【发布时间】:2017-10-02 22:22:22
【问题描述】:

抱歉,这是一个非常基本的问题,但我希望从一个 Firebase 表中获取用户 ID,并使用该用户 ID 从另一个 Firebase 表中提取数据。在第一个函数中,我调用 fetchUserData 函数来根据给定的用户 ID 获取我的用户的名字。我可以提取名字,但是如何将它返回到我的第一个函数,以便我可以将它插入到 append 方法中。

func fetchList() {

    let currentUser = Auth.auth().currentUser!

    let postRef = self.databaseRef.child("List").child(currentUser.uid)

    postRef.observe(.value, with: { (snapshot) in
        for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
            let userid = childSnapshot.key

            self.fetchUserData(uid: userid)

            self.userArray.append(User(firstname: "Need to get from fetchUserData", uid: userid))

            self.tableView.reloadData()

        }
    })
}

func fetchUserData(uid: String){

    let currentUserRef = databaseRef.child("users").child(uid)

    currentUserRef.observeSingleEvent(of: .value, with: { (snapshot) in
        //fetch firstname based on given uid
        let value = snapshot.value as? NSDictionary
        let firstname = value?["firstname"] as? String ?? ""

    })
}

【问题讨论】:

  • 这不起作用,因为它是一个侦听器,并且肯定不会完全返回/一次。只需将您的代码从fetchUserData 放入postRef.observe 并将append 放入currentUserRef.observe

标签: swift firebase swift3 firebase-realtime-database


【解决方案1】:

你可以这样使用:

func fetchList() {
    let currentUser = Auth.auth().currentUser!
    let postRef = self.databaseRef.child("List").child(currentUser.uid)

    postRef.observe(.value, with: { (snapshot) in
        for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
            let userid = childSnapshot.key

            self.fetchUserData(uid: userid, callback: { (firstName) in
                self.userArray.append(User(firstname: firstName, uid: userid))
                self.tableView.reloadData()
            })
        }
    })
}

func fetchUserData(uid: String, callback: @escaping (_ firstname: String)->Void){

    let currentUserRef = databaseRef.child("users").child(uid)

    currentUserRef.observeSingleEvent(of: .value, with: { (snapshot) in
        //fetch firstname based on given uid
        let value = snapshot.value as? NSDictionary
        let firstname = value?["firstname"] as? String ?? ""
        callback(firstname)
    })
}

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2016-02-11
    相关资源
    最近更新 更多