简体   繁体   中英

How to retrieve data of current user from firebase

I'm, developing a simple app to store users images. User authorized via Facebook, and the interact with app. I stuck with retrieving data from current user.

In my firebase for now I have such structure: 在此输入图像描述

I decided to get user data by uid. So I initialized variable

let userID = FIRAuth.auth()?.currentUser?.uid

Then I retrieve an array of objects from my database

URL_BASE.child("profile").observeEventType(.Value, withBlock: { (snapshot) in

    print (snapshot.value as! [String:AnyObject]!)

})

}

In my output I have this:

 "-KJSKE4a2y-okl71vDSx": {
    Interest = men;
    gender = female;
    name = girlsname1;
    photo = "http://i.imgur.com/VAWlQ0S.gif";
    surname = girlsurname1;
}, "-KJSKE4b8TlvxV-urHQo": {
    Interest = men;
    gender = female;
    name = girlsname6;
    photo = "http://media.tumblr.com/tumblr_lnb9aozmM71qbxrlp.gif";
    surname = girlsurname6;

And so on

It is ok, but my goal is to print data of currently authorized user. I have an idea of sorting all objects by uid, but I think it is irrational. Hope there is simpler solution.

Authorized users stores in users database. profile database consist of user parameters I'm getting from Facebook.

In Firebase, all users have a uid as you know. The uid should be used as the key for each user node in /users.

uid_0
  gender: male
  name: Leroy
uid_1
  gender: female?
  name: pat

This is a common design pattern in Firebase.

With that, you can simply get any user by their uid

let thisUserRef = usersRef.childByAppendingPath("the uid")

thisUserRef.observeSingleEventOfType(.Value... {
    let gender = snapshot.value["gender"]
}
    let userID : String = (FIRAuth.auth()?.currentUser?.uid)!
    print("Current user ID is" + userID)

   self.dbRef?.child("profile").child(userID).observeSingleEvent(of: .value, with: {(snapshot) in
        print(snapshot.value)

        let userEmail = (snapshot.value as! NSDictionary)["addedByUser"] as! String
        print(userEmail)


    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM