Firebase how to create users? - swift

I am not familiar with the new Firebase. How do I create new users? The code below I Signup and auth new user. If I need to create this new user under "Customers" in Firebase Database, what code do I need to add? Thanks!
FIRAuth.auth()?.createUserWithEmail(email, password: password, completion: { (user, err) in
if err != nil {
self.showAlert("Can't Register", msg: "Please enter email and password")
} else {
NSUserDefaults.standardUserDefaults().setValue(user?.uid, forKey: "uid")
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (user, error) in
})
self.performSegueWithIdentifier("toSecondVC", sender: self)
}
})

FIRAuth.auth()?.createUserWithEmail(email, password: password, completion: { (user, err) in
if err != nil {
self.showAlert("Can't Register", msg: "Please enter email and password")
} else {
NSUserDefaults.standardUserDefaults().setValue(user?.uid, forKey: "uid")
FIRDatabase.database().reference().child("Customers").setValue([user!.uid : "true"])
//Or if you want to save the users Details too:-
/*
FIRDatabase.database().reference().child("Customers").setValue([user!.uid : ["email" : email,"password" : password]])
*/
self.performSegueWithIdentifier("toSecondVC", sender: self)
}
})
Also might i suggest reading this : Firebase iOS - Save Data

The answer above is correct, but I'd recommend doing it this way:
var values = [Any : Any] // This is a dictionary where you can store user details
values["userUID"] = // user's uid
values["usersName"] = // user's name
// etc.
let customerRef = databaseReference.child("Customers") // You could also add a child with the user's UID in order to identify each user
customerRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
if error != nil {
// display error.code and error.localizedDescription to user if needed
} else if ref != [] {
// Success!
// If needed, save the user to NSUserDefaults and perfrom a segue to another ViewController
} else {
// There was an error, but not sure what happened. Let the user know how they can fix the problem (maybe add the details to the database later)
}
})

Related

Swift retrieve user info from firebase firebase firestore

I want to retrieve the current logged in user Information (name and email) that was stored in the firestore in the registration function, the email and name should be displayed in textfield.
I can retrieve the email successfully because I’m using the Auth.auth().currentUser and not interacting with the firesotre while the name is not working for me.
what I’m suspecting is that the path I’m using for reaching the name field in firesotre is incorrect.
var id = ""
var email = ""
override func viewDidLoad() {
super.viewDidLoad()
userLoggedIn()
self.txtEmail.text = email
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getName { (name) in
if let name = name {
self.txtUserName.text = name
print("great success")
}
}
}
func getName(completion: #escaping (_ name: String?) -> Void) {
guard let uid = Auth.auth().currentUser?.uid else { // safely unwrap the uid; avoid force unwrapping with !
completion(nil) // user is not logged in; return nil
return
}
print (uid)
Firestore.firestore().collection("users").document(uid).getDocument { (docSnapshot, error) in
if let doc = docSnapshot {
if let name = doc.get("name") as? String {
completion(name) // success; return name
} else {
print("error getting field")
completion(nil) // error getting field; return nil
}
} else {
if let error = error {
print(error)
}
completion(nil) // error getting document; return nil
}
}
}
func userLoggedIn() {
if Auth.auth().currentUser != nil {
id = Auth.auth().currentUser!.uid
//email = Auth.auth().currentUser!.email
} else {
print("user is not logged in")
//User Not logged in
}
if Auth.auth().currentUser != nil {
email = Auth.auth().currentUser!.email!
} else {
print("user is not logged in")
//User Not logged in
}
}
When I run this code the email is displayed and for the name "error getting field" gets printed so what I think is that the name of the document for user is not the same as the uid therefore the path I’m using is incorrect, the document name must be autogenerated.
So is the solution for me to change the code of the registration function?
can the user document be given a name (the userID) when I create the user document, instead of it being auto generarte it, if that’s even the case.
Here is the registration code for adding documents to firestore:
let database = Firestore.firestore()
database.collection("users").addDocument(data: [ "name" :name, "email" : email ]) { (error) in
if error != nil {
//
}
an here is a snapshot of my firestore users collection
When creating a user;
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
  // ...
}
At first you can only save email and password. (For now, that's how I know.)
But after you create the user, you can update the user's name.
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = displayName
changeRequest?.commitChanges { error in
  // ...
}
Use userUID when saving user information in Firestore.
If you drop the document into firebase, it will create it automatically. But if you save the user uid, it will be easy to access and edit.
func userSave() {
let userUID = Auth.auth().currentUser?.uid
let data = ["name": "ABCD", "email": "abcd#abcd.com"]
Firestore.firestore().collection("users").document(userUID!).setData(data) { error in
if error != nil {
// ERROR
}
else {
// SUCCESSFUL
}
}
}
If you are saving user information in Firestore, you can retrieve information very easily.
func fetchUser() {
let userUID = Auth.auth().currentUser?.uid
Firestore.firestore().collection("users").document(userUID!).getDocument { snapshot, error in
if error != nil {
// ERROR
}
else {
let userName = snapshot?.get("name")
}
}
}
For more detailed and precise information: Cloud Firestore Documentation
If you see missing or incorrect information, please warn. I will fix it.
There's a distinction between a Firebase User property displayName and then other data you're stored in the Firestore database.
I think from your question you're storing other user data (a name in this case) in the Firestore database. The problem is where you're storing it is not the same as where you're reading it from.
According to your code here's where it's stored
database.collection("users").addDocument(data: [ "name" :name,
which looks like this
firestore
users
a 'randomly' generated documentID <- not the users uid
name: ABCD
email: abcd#email.com
and that's because addDocument creates a documentID for you
Where you're trying to read it from is the actual users UID, not the auto-created documentID from above
Firestore.firestore().collection("users").document(userUID!)
which looks like this
firestore
users
the_actual_users_uid <- the users uid
name: ABCD
email: abcd#email.com
The fix it easy, store the data using the users uid to start with
database.collection("users").document(uid).setData(["name" :name,

How/when to remove Firebase Auth listener after registration & write to database?

I'm using Firebase email/password authentication and writing a username and other information to my database. To write to DB I'm using the auth listener as recommended in the documentation:
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
// ...
}
The problem I'm having is that when I log the user out, then log back in the listener fires again and overwrites my database information. So I'm trying to figure out how to remove the listener after it fires the first time.
I've tried the to remove the listener using:
Auth.auth().removeStateDidChangeListener(listener)
But this removes the listener before it has time to write to my database.
This may be simple, but how can I write this to delay removing the listener until after it fires the first time writing to the database?
I've tried in a few places, and I've looked for some alternatives, but I haven't seen anything that solves this which was surprising to me as it seems this would be a very common situation.
Here is the code I'm using to create the account and write to the database:
#IBAction func nextButtonTapped(_ sender: UIButton) {
validate()
if usernameTakenLabel.isHidden == false {
nextButton.isEnabled = false
}
// Create Account w/ email
let usersRef = Database.database().reference().child("users")
let usernamesRef =
Database.database().reference().child("usernameRef")
if username != "" && email != "" && password != "" {
Auth.auth().createUser(withEmail: emailTextfield.text!, password: passwordTextfield.text!) { (user, error) in
print("New User successfully created")
}
self.listener = Auth.auth().addStateDidChangeListener { (auth, user) in
if let user = user {
//Write username to the database
usersRef.child(user.uid).setValue(["username": username])
usernamesRef.childByAutoId().setValue(username)
print("username successfully created")
}
}
//PROBLEM:
//How can I delay this until after the code above runs?
Auth.auth().removeStateDidChangeListener(listener!)
}
}
Any and all help much appreciated!
You need to add a completion block , whenever the task gets completed then we can call further method.
func checkUser(completion:() -> Void)
{
// Create Account w/ email
let usersRef = Database.database().reference().child("users")
let usernamesRef =
Database.database().reference().child("usernameRef")
if username != "" && email != "" && password != "" {
Auth.auth().createUser(withEmail: emailTextfield.text!, password: passwordTextfield.text!) { (user, error) in
print("New User successfully created")
}
self.listener = Auth.auth().addStateDidChangeListener { (auth, user) in
if let user = user {
//Write username to the database
usersRef.child(user.uid).setValue(["username": username])
usernamesRef.childByAutoId().setValue(username)
print("username successfully created")
//call this whenever the the task is completed
completion()
}
}
//you can also call this function here
//Auth.auth().removeStateDidChangeListener(listener!)
}
}
checkUser
{
print("task Completed")
Auth.auth().removeStateDidChangeListener(listener!)
}

Swift closures and error handling

hello, i need some help with function and or possibly closures in that function. I want my function to check the firestore users collection for duplicate documents (usernames). If a duplicate is found i want to display a message, if a duplicate is not found, create a new user. i have folowing code:
func checkIfUserExists(username: String, completion: #escaping (Bool) -> Void) {
let docRef = db.collection("users").document(username)
docRef.getDocument { (document, error) in
if error != nil {
print(error)
} else {
if let document = document {
if document.exists {
completion(true)
} else {
completion(false)
}
}
}
}
}
and i call the function with:
if let username = textField.text, username.count > 8 { // Username needs to be more then 8 Char
checkIfUserExists(username: username) { (doesExist) in
if doesExist {
print("user exists")
} else {
print("new User can be created")
}
}
} else {
print("Username needs to be more then 8 char")
}
}
It works, but i have the feeling it is not good practice and i'm making detours. Is this the right way to do it ?
I think the way you're doing it now should work well, but another option to prevent you from having to do a read of the database before writing is to use security rules. For example, if this is the structure of your users collection...
users: [
username1: { // doc ID is the username
userid: abcFirebaseUserId, // a field for the uid of the owner of the username
//...etc
}
]
...then you can use the following rules:
match /users/{username} {
allow create: if request.auth.uid != null;
allow update, delete: if resource.data.userId = request.auth.uid;
}
This allows any authenticated user to create a new username, but only the owner of that username can update it or delete it. If you aren't allowing users to change their username, you wouldn't even have to worry about the second rule. Then, in the client, you go right to creating a username, like so:
func createUsername(username: String, completion: #escaping (String?) -> Void) {
guard let userId = Auth.auth().currentUser.uid else {
completion("no current user")
return
}
let docRef = db.collection("users").document(username)
docRef.setData(data:[userId: userId]) { error in
if let error = error {
completion(error.debugDescription)
} else {
completion(nil)
}
}
}
This would write the new username to the database and pass an error to the closure if there is one. If the username already exists, an insufficient permissions error would be present. When checking if the user exists, you could display the error or alert the user however you wanted.
createUsername(username: username) { err in
if let err = err {
print("user exists")
} else {
print("new User has been created")
}
}
Just a suggestion though. I think they way you're doing it now is fine, too!

ERROR is value of type 'AuthDataResult' has no member 'uid'?

My codes error
I do not know why its saying that 'uid' has no member, also i don't know where AuthDataResult is coming from because i have never used this as an import or anything along those lines...
#IBAction func signinPressed(_ sender: Any) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().signIn(withEmail: email, password: password) { (user, error )
in
if error != nil{
//create account
} else {
KeychainWrapper.standard.set((user?.uid)!,
forKey: ("Key_UID"))
self.preformSegue(performSegue(withIdentifier: "toFeed", sender: nil))
}
}
}
}
The error you get is:
Value of type AuthDataResult has no member uid
If you look at the reference documentation for AuthDataResult, you'll see that this is correct: there is no uid in that class. The uid property exists in FIRUser, so you'll want to use:
user?.user.uid
Or to make it less confusing, give your current user variable a name that better matches what it is:
Auth.auth().signIn(withEmail: email, password: password) { (authData, error ) in
if error != nil{
//create account
} else {
KeychainWrapper.standard.set((authData?.user.uid)!,
forKey: ("Key_UID"))
self.preformSegue(performSegue(withIdentifier: "toFeed", sender: nil))
}
}

How can I verify if a username on Firebase is available?

In my Swift app, when signing up a user, the user is prompted to select a username. This username will then be stored in the Firebase realtime database like this: self.ref.child("users").child(user!.uid).setValue(["username": usernameResponse]), where username response is the value entered by the user. This happens as part of the sign up method:
FIRAuth.auth()?.createUserWithEmail(email, password: passwordUltimate) { (user, error) in
// ... if error != nil {
I would like to verify if the username is available before setting its value. Is there some kind of query I could use to check that there are no duplicates?
Here is my database with some sample data (qwerty12345 is the uid):
#IBAction func enterUsername(){
let enteredUsername = usernameText!.text!
let namesRef = ref.childByAppendingPath("/usernames/\(enteredUsername)")
namesRef.observeSingleEventType(.Value, withBlock: {
snap in
if (snap.value is NSNull){
let userNameAndUUID = ["Username" : enteredUsername, "UUID" : self.appDelegate.UUID]
namesRef.setValue(userNameAndUUID)
print("first block")
}else {
print("second block")
//do some other stuff
}
})
}
Alternately:
let checkWaitingRef = Firebase(url:"https://test.firebaseio.com/users")
checkWaitingRef.queryOrderedByChild("username").queryEqualToValue("\(username!)")
.observeEventType(.Value, withBlock: { snapshot in
if ( snapshot.value is NSNull ) {
print("not found)")
} else {
print(snapshot.value)
}
}