Skip to content

Instantly share code, notes, and snippets.

@haIIux
Last active March 2, 2022 18:17
Show Gist options
  • Save haIIux/45e4e54ea5d149a454d907ac2a68d5cc to your computer and use it in GitHub Desktop.
Save haIIux/45e4e54ea5d149a454d907ac2a68d5cc to your computer and use it in GitHub Desktop.
Firebase authentication view model creation.
import Firebase
// MARK: - Create our class of type ObservableObject which will allow us to access @Published variables we will create later.
class AuthViewModel: ObservableObject {
// MARK: - We're going to create two private let's, remember that let's are constants and cannot be mutated. Private means that we can only access those lets here in this file and no where else. The auth variable allows us to access Firebase Authentication methods and such, the firestore will allow us to access the Firestore ones.
private let auth = Auth.auth()
private let firestore = Firestore.firestore()
// MARK: - This is our registration function which allows us to simultaneously create a user within the authentication system and a entry within our Firestore database which allows for saving additional information.
func registerUser(withEmail email: String, password: String, fullname: String, username: String) {
// MARK: - As you can see here, we're using our private let "auth" to keep this simple. We're accessing the .createUser(withEmail ...) method within Firebase Authentication platform. We're catching our errors and then protection our result which could be optional.
auth.createUser(withEmail: email, password: password) { result, error in
if let error = error {
print("DEBUG : Failed to register user with \(error.localizedDescription)")
return
}
guard let user = result?.user else { return }
// MARK: - This let allows us to map out our data which will be added to our Firestore. This is the spot you would add any additional data you want to store from the user that is not just their basic email and password.
let data = ["email" : email,
"username" : username.lowercased(),
"fullname" : fullname,
"uid" : user.uid]
// MARK: - This "self.firestore" is accessing our firestore let above in line 15 which once again accesses methods within Firebase Firestore.
self.firestore.collection("users")
.document(user.uid)
.setData(data) { error in
if let error = error {
print("DEBUG : Failed to add user to collection with \(error.localizedDescription)")
return
}
print("DEBUG : User data set.")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment