Fetch User Info and append to an Array

我们两清 提交于 2019-12-13 03:53:57

问题


Sorry if this is a very basic question, but I'm looking to fetch a userId from one Firebase table and use that userId to pull data from another Firebase table. In the first function, I call a fetchUserData function to get the firstname of my user based on a given userid. I'm able to pull the firstname, but then how do I return it to my first function so that I can insert it in the append method.

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 ?? ""

    })
}

回答1:


You can use like this:

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)
    })
}


来源:https://stackoverflow.com/questions/46534571/fetch-user-info-and-append-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!