Jason Tremain
Jason Tremain

Reputation: 1399

Add user using Authentication + Create User

Currently, I have successfully implemented allowing a user to create an account using an email address and password and inserting that info into Firebase Authentication. What I'm trying to figure out now is how to simultaneously take the information entered in the sign up form and insert a new record into FireStore. I'd like to insert the user's email address, first and last name as a record.

I've tried adding the code to insert the record inside of my "SignUp" function, but that seems to break the function. Below is the working code followed by the code I tried that didn't work.

//Working Code

struct SignUpView: View {
@State var email: String = ""
@State var password: String = ""
@State var error: String = ""


@EnvironmentObject var session: SessionStore
let db = Firestore.firestore()

func signUp() {
    session.signUp(email: email, password: password) { (result, error) in
        if let error = error {
            self.error = error.localizedDescription
        } else {
            self.email = ""
            self.password = ""
        }
    }

}    

//Does Not Work (Error: Type 'SignUpView' does not conform to protocol 'View')

struct SignUpView: View {
@State var email: String = ""
@State var password: String = ""
@State var error: String = ""
@State var fname: String = ""
@State var lname: String = ""

@EnvironmentObject var session: SessionStore
let db = Firestore.firestore()

func signUp() {
    session.signUp(email: email, password: password) { (result, error) in
        if let error = error {
            self.error = error.localizedDescription
        } else {
            self.email = ""
            self.password = ""
        }
    }
    // Insert record into Users collection
    db.collection("users").addDocument(data: [
            "fname": fname,
            "lname":lname,
            "email": email ])
    }
    // End Insert
} 

Upvotes: 0

Views: 207

Answers (2)

Tobias Hesselink
Tobias Hesselink

Reputation: 1647

Adding a user model to Firestore in SwiftUI is very simple. I used a completionBlock to handle completion, you can show a loading indicator till the function returned a value. This may be useful for all queries.

The following code will add a user to Firestore:

func addUserToDatabase(name: String, email: String, phone: String, completionBlock: @escaping (_ success: Bool) -> Void) {
    let accountData = [
        "name" : name,
        "email" : email,
        "phone" : phone
    ]

    db.collection("users").document(self.user.id).setData(accountData) { err in
        if err != nil {
            completionBlock(false)
        } else {
            completionBlock(true)
        }
    }
}

Note that: 'self.user.id' is the user ID from the authentication. So when you create a user in the firebaseAuth, a unique ID will be created, you can store this ID in your app so you can create a reference in your database. Useful for easily removing or changing user's data.

Example of using this method in your app

self.addUserToDatabase(name: name, email: email, phone: phone) { (succes) in
    if (succes) {
        print("User added to the database")
        UserDefaults.standard.set(self.user.id, forKey: "uid_current_user")
        completionBlock(true)
    } else {
        print("Something went wrong when trying to add user to the database")
        completionBlock(false)
     }
}

Upvotes: 1

PaFi
PaFi

Reputation: 920

Session.SignUp is asynchronous.

struct SignUpView: View {
@State var email: String = ""
@State var password: String = ""
@State var error: String = ""
@State var fname: String = ""
@State var lname: String = ""

@EnvironmentObject var session: SessionStore
let db = Firestore.firestore()

func signUp() {
    session.signUp(email: email, password: password) { (result, error) in
        if let error = error {
            self.error = error.localizedDescription
        } else {
            self.email = ""
            self.password = ""
// Insert record into Users collection
    db.collection("users").addDocument(data: [
            "fname": self.fname,
            "lname":self.lname,
            "email": self.email ])
    }
    // End Insert

        }
    }

} 

But the code you posted can not be the full code for your SignUpView because it needs to contain

var body: some View {}

Upvotes: 2

Related Questions