16

I'm using Firebaseauth to manage users and data for my iOS app. The users can log in, and their userinfo is stored correct in the database. But when I try to get the users to write to the database in a different viewController, using this string:

self.ref.child("users").child(user.uid).setValue(["username": username])

The thrown error is

Type user has no member .uid

That makes sense I guess, since I haven't created the variable. But I can't figure out how to declare it?

KENdi
  • 7,576
  • 2
  • 16
  • 31
Eccles
  • 394
  • 1
  • 3
  • 13
  • You're supposed to pass the info to the next view controller. [This](https://code.tutsplus.com/tutorials/ios-sdk-passing-data-between-controllers-in-swift--cms-27151) will be helpful – eshirima Jun 06 '17 at 13:53

3 Answers3

45

This is how you get the user's uid:

let userID = Auth.auth().currentUser!.uid

UPDATE: Since this answer is getting upvotes, make sure you prevent your app from crashing by using guards:

guard let userID = Auth.auth().currentUser?.uid else { return }
9

You might want to use a guard, as a force unwrap might break your app if a user isn’t signed in.

guard let userID = Auth.auth().currentUser?.uid else { return }
Victor
  • 319
  • 4
  • 5
1

FIRAuth has actually been renamed to Auth. So, as per the latest changes, it will be

let userID = Auth.auth().currentUser!.uid

Edit.

As pointed out in comments, A force unwrap may crash the app.

guard let userID = Auth.auth().currentUser?.uid else { return }
The Doctor
  • 486
  • 1
  • 6
  • 16