Fetch User Info and append to an Array

2019-08-25 09:39发布

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条回答
倾城 Initia
2楼-- · 2019-08-25 10:11

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)
    })
}
查看更多
登录 后发表回答