Tamannah Tamannah - 3 years ago 82
iOS Question

How do I link each user to their data in Firebase for Swift 3?

I have created a project integrated with Firebase. It has signup and login features. I have personal information form to fill up for individual users. But when the users are different, all data are shown for all users. I need to show information related to linked users. The person should only be able to access his/her database. I couldn't find proper solution in Swift 3.

Answer Source

From best I can tell it seems you are not referencing the correct node in your database. You are seeing all of your users data because your variable messageRef is pointed at /users. If you'd like users to only see their data then you need to organize your data so that when you save a messageItem that is is at /users/{user_id}. Then properly access it by first getting the user_id and reading it from it's new location (/users/{user_id}).

so I'd change these lines from this:

override func viewDidLoad() {
    super.viewDidLoad()

       messageRef = databaseRef.child("Users")

    // Do any additional setup after loading the view.
}

to this:

override func viewDidLoad() {
    super.viewDidLoad()
       guard let user = Auth.auth().currentUser else { return }
       messageRef = databaseRef.child("Users/\(user.uid)")
    // Do any additional setup after loading the view.
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download