SwiftUI Edit User Account using data from Firestore - ios

I'm very new to SwiftUI and I'm trying to create a very basic login/logout system in SwiftUI on IOS with the ability to edit the users profile. I have two main functions in the signup process, function register and function AddInfo which then actually adds the user to the db.
both in AuthenticationView.swift
func register(){
if self.email != ""{
if self.pass == self.repass{
//Creating the user
Auth.auth().createUser(withEmail: self.email, password: self.pass) { (res, err) in
if err != nil{
self.error = err!.localizedDescription
self.alert.toggle()
return
}
//Add user info to database
AddInfo(username: self.username, email: self.email)
print("success")
UserDefaults.standard.set(true, forKey: "status")
NotificationCenter.default.post(name: NSNotification.Name("status"), object: nil)
}
}
else{
self.error = "Password mismatch"
self.alert.toggle()
}
}
else{
self.error = "Please fill all the contents properly"
self.alert.toggle()
}
}
Then i have an addinfo function which adds the user to a database. The document ID of the db is the users UID and then it creates a username, email and uid automatically and i've made it create a blank entry for Firstname and Lastname.
func AddInfo(username: String, email: String) {
let db = Firestore.firestore()
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let uid = user.uid
//let email = user.email
//let photoURL = user.photoURL
db.collection("users").document(uid).setData([
"UID": uid,
"Username": username,
"Email": email,
"First Name": "",
"Last Name": ""])
}
This is what the DB looks like when a user registers
database look when user registers
So with all of this in mine, i'm struggling with creating a Edit user profile view. How would I go about doing this? All i need is a page that shows the users registered email, username and then they can add their first and last name (first and last name isn't included on the registration form, that's something i'd like to add after they've registered)
I've tried reading the Firestore view my profile document but i'm struggling to get my head around it

Related

why do i get two user ids when creating a user in firebase using swift?

when i sign up a user in my ios app it generates a user id and adds that to the data base with the users name and surname and username but it is generating a user id and another random number/id and i dont know what that is for:
i dont know what the Roy... is and dont know where its coming from.
so when i try and access the users uid to access the information such as the name and surname i keep getting the following error because its using the wc7... number and not the other one:
Listener at /Users/wc7VyejKlDNfcAhFu3AkIX9Y9on1/Username failed: permission_denied
this is my code that i use to try and access the users information:
func fetchUsersData() {
guard let currentUser = Auth.auth().currentUser?.uid else { return }
print("Current user id is \(currentUser)")
Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
guard let username = snapshot.value as? String else {return}
self.navigationItem.title = username
}
}
how do i fix this?
That code is for the Firebase Real Time Database and the screen shot is for Cloud Firestore. They are totally different and unrelated.
If you want to read the data shown in your screenshot you need to use the Cloud Firestore documentation.
The documentID 'Roy...' happens when you don't assign a document an ID... it will generate one automatically.
Also, change your Firestore structure to use the users uid as the documentID. So it would look like this
users //the collection
uid_0 //the document with documentID = a users uid
first_name: "Hank"
last_name: "Jones"
user_name: "Hankster"
uid_1
first_name: "Leroy"
last_name: "Jenkins"
user_name: "Leeeerrroooyyy"
and then the code to read a specific user name based on a uid is this
func readUserName() {
let users = self.db.collection("users")
let thisUser = users.document(the users uid)
thisUser.getDocument(completion: { documentSnapshot, error in
if let error = error {
print(error.localizedDescription)
return
}
guard let snap = documentSnapshot else { return }
let docId = snap.documentID
let userName = snap.get("user_name") as? String ?? "No Name"
print(userName)
})
}
Also note that you will need to be authenticated to Firestore to read any data or adjust the Security Rules to allow anyone to read. That's not generally a good idea but when you're just getting started it's ok.

Insert instead of update in firebase

I'm trying to insert new values into Firebase Realtime Database. But every time I "register" a new user, my database data is getting replaced by the new one. I'm totally confused on how I can do this different.
This is my code..
//Create a new user with txtfield email & password
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
//Printing error if any
if error != nil
{
print(error as Any)
return
}
//Getting database reference
let ref = Database.database().reference()
//Values to insert into database
let values = ["Username": self.username, "Email": self.email, "Name1": self.name1, "Name2": self.name2, "Name3": self.name3, "Name4": self.name4, "Name5": self.name5, "Name6": self.name6, "Dog1": dog1, "Dog2": dog2, "Dog3": dog3]
//Updating the child values
ref.updateChildValues(values, withCompletionBlock: { (err, ref) in
//Printing error if any
if err != nil
{
print(err as Any)
return
}
//Succeded if no errors
print("Saved user successfully in Firebase database!")
})
And I assume the problem is at
ref.updateChildValues(values, withCompletionBlock: { (err, ref) in
But I've no idea how I can replace this. So to make it short.
Every time I create a new user, the database data is getting replaced. And I basically want it to create a new "row" for each user.
You need to insert the items under a child like users/userID
guard let firUser = authResult.user else { return }
let userID = firUser.uid
let ref = Database.database().reference()
let user = ref.child("users/\(userID)")
user.updateChildValues////
Database
> users
> njfjnjnf889489489 // some user uid
> name
> mail
> 322jnjnf889489483 // some user uid
> name
> mail

Swift Firebase -How can I verify the `PhoneAuthCredential` and keep the user currently signed in with their current email uid

Users sign into my app with email authentication. Once inside they can browse and search for different things. But if the user wants to post they have to verify their phone number (if they don't want to post their phone number isn't necessary).
The phone number and sms process works fine but once I authenticate the PhoneAuthCredential the uid associated with the email that the user is currently signed in with is replaced with the uid generated from the phone credential. This creates a situation where an entirely new user is inside the app and because of this they don't have access to any of their data (anything associated with the uid from the email).
Basically the Auth.auth().currentUser?.uid was initially the email's uid and now the Auth.auth().currentUser?.uid would be the phone's uid
How can I verify the PhoneAuthCredential and keep the user currently signed in with their current email uid?
var emailUid: String? // a6UVVWWN4CeTCLwvkn...
var verificationId: String?
var phoneUid: String? // tUi502DnKlc19U14xSidP8
// 1. user signs into the app with their email address and their uid is a6UVVWWN4CeTCLwvkn...
Auth.auth().signIn(withEmail: emailTextField.text!, password: self.passwordTextField.text!, completion: {
(authDataResult: AuthDataResult?, error) in
self.emailUid = authDataResult?.user.uid // a6UVVWWN4CeTCLwvkn...
})
// 2. user goes to post something but before they can post they have to verify their phone number
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumberTextfield.text!, uiDelegate: nil) {
(verificationID, error) in
guard let verificationID = verificationID else { return }
self.verificationId = verificationID
}
// 3. sms code is sent to user's phone and they enter it
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationId!, verificationCode: smsTextField.text!)
// 4. now VERIFY sms code by signing the user in with the PhoneAuthCredential
Auth.auth().signInAndRetrieveData(with: credential, completion: {
(authDataResult, error) in
self.phoneUid = authDataResult?.user.uid // tUi502DnKlc19U14xSidP8 this is now the current user's uid
// 5. save phoneNumber and verificationId to the user's uid ref associated with the EMAIL address
var dict = [String: Any]()
dict.updateValue(verificationId!, forKey: "verificationId")
dict.updateValue(phoneNumberTextfield.text!, forKey: "phoneNumber")
dict.updateValue(self.phoneUid!, forKey: "phoneUid")
if Auth.auth().currentUser!.uid == self.emailUid! {
// THIS WILL NEVER RUN
let emailUidRef = Database.database().reference().child("users").child(emailUid!)
emailUidRef?.updateChildValues(dict)
}
})
You can link the two accounts together using Firebase Authentication's account linking. As that documentation says:
Complete the sign-in flow for the new authentication provider up to, but not including, calling one of the FirebaseAuth.signInWith methods.
So you skip signInAndRetrieveData(with: credential), but instead call User.linkAndRetrieveData(with: credential). Once the accounts are linked, you can sign in with either of them to get the "combined" authenticated user.

Swift iOS Firebase -If the FirebaseAuth.FIRUser Object isn't nil how is it possible for the .email on it to return nil?

I use Firebase's Email/Password Sign-In Method to create an account for a user. Using that method the user must have an email address to get authenticated into Firebase.
FirebaseAuth has a FIRUser object named User
When a user first creates an account or logs into an existing account in the callback the User object gets initialized:
Create Account:
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: {
(user, error) in
// user's auth credentials are now created but user can still be nil
Logging into existing account:
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!, completion: {
(user, error) in
// user's auth credentials are now accessed but user can still be nil
The User object has an .email Optional of type String on it that contain's the user's email address.
I use a singleton class to manage everything that happens through Firebase and in both situations above when the User objects gets initialized I pass that data through to my Firebase singleton's class properties. I know the User object can come back as nil so I run an if-let to make sure it isn't.
My question is if using the Email/Password Sign-In Method if the User object isn't nil in the callback is it possible that the .email can be nil even though it's necessary to have it to make an account or log in?
After I run the if-let statements I use guard statements to check and see if the .email isn't nil but it seems like it either can run before the the FirebaseSingleton properties gets initialized (which means it will be nil) or it might be unnecessary if the User object is guaranteed to return it with a value.
Btw in both situations wether the user is creating and account or logging in the emailTextFiled and passwordTextField will not be nil. I run whitespace, .isEmpty, and != nil checks on them.
My Code:
class FirebaseSingleton{
static let sharedInstance = FirebaseSingleton()
var dbRef: DatabaseReference? = Database.database().reference()
var storageDbRef: StorageReference? = Storage.storage().reference(forURL: "gs://blablabla.appspot.com")
var currentUser: User? = Auth.auth().currentUser
var currentUserID: String? = Auth.auth().currentUser?.uid
var currentUserEmail: String? = Auth.auth().currentUser?.email
var currentUserPhotoUrl: URL? = Auth.auth().currentUser?.photoURL
var currentUserDisplayName: String? = Auth.auth().currentUser?.displayName
}
Creating an Account:
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: {
(user, error) in
if error != nil { return }
if let user = user{
let sharedInstance = FirebaseSingleton.sharedInstance
sharedInstance.currentUser = user
sharedInstance.currentUserID = user.uid
sharedInstance.currentUserEmail = user.email // at this point is it possible for this to be nil?
sharedInstance.currentUserPhotoUrl = user.photoURL
sharedInstance.currentUserDisplayName = user.displayName
}else{
return
}
// is this guard statement necessary?
guard let email = user.uid else { return }
})
Logging into an existing account:
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: {
(user, error) in
if error != nil { return }
if let user = user{
let sharedInstance = FirebaseSingleton.sharedInstance
sharedInstance.currentUser = user
sharedInstance.currentUserID = user.uid
sharedInstance.currentUserEmail = user.email // at this point is it possible for this to be nil?
sharedInstance.currentUserPhotoUrl = user.photoURL
sharedInstance.currentUserDisplayName = user.displayName
}else{
return
}
// is this guard statements necessary?
guard let email = user.uid else { return }
})
Not sure exactly what are you asking for (since to me looks more like a swift question than a firebase one), but as long as the user isn't nil, the uid property is not an optional (String) so user.uid will never be nil. it is not the same for the email which is an String? therefore might or not be nil
After having a convo with #Benjamin Jimenez and per #kbunarjo suggestions I did some thinking and I realized that Firebase also has a Phone Sign-In Method. If it's enabled and a user chooses that as their sign-in method then the .email address would be nil because there wouldn't be an email address used to create an account.
For my situation since I'm using the Email/Password Sign-In Method then the .email should not be nil because it is the only way to create an account. But just as User can come back as nil in the completion handler (even with the correct email and password) maybe it’s possible that the email address can also come back as nil since it’s an Optional.
That being said the safest method to use would be another if-let to check to see if the user.email isn't nil and if for some strange reason that it is then use the email address that was entered into the emailTextField as an alternative. The email address entered into the emailTextField and password combo has to be correct otherwise the user won't get authenticated into Firebase and error != nil.
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: {
(user, error) in
// if the email address and/or password are incorrect then error != nil and the code below this wont run
if error != nil { return }
if let user = user{
let sharedInstance = FirebaseSingleton.sharedInstance
sharedInstance.currentUser = user
sharedInstance.currentUserID = user.uid
sharedInstance.currentUserPhotoUrl = user.photoURL
sharedInstance.currentUserDisplayName = user.displayName
// instead of the guard statement I use another ‘if-let’ if for some reason .email is nil
if let currentUserEmail = user.email {
sharedInstance.currentUserEmail = currentUserEmail
}else{
sharedInstance.currentUserEmail = self.emailTextField.text! // the email address entered into here has to be valid otherwise it would've never made it to this point
}
}else{
return
}
})
Use the same exact code for the callback if Creating an Account
As #rMickeyD noted the Facebook Sign-In Method won’t use the email address either. I’ve never used it so I didn’t include it. Basically if none of the other Sign-In Methods don’t use your email address then user.email will be nil. Even if though I have Anonymous Sign-In as an option the method to use Anonymous Sign-In doesn’t require an email address nor a password so it’s understood that email will be nil.
You should check the docs to see if they require the email or not for all the other Sign-In Methods but the Phone number doesn’t need it.

How to add a username to Firebase database upon registration?

Upon logging in I want my app to make a new field in the Firebase database with the child named after the username.
if let email = emailField.text, let pass = passwordField.text {
// Check if it's sign in or register
if isLogin {
// Sign in the user with Firebase
Auth.auth().signIn(withEmail: email, password: pass, completion: { (user, error) in
// Check that user isn't nil
if let u = user {
// User is found, go to home screen
self.ref?.child(email).childByAutoId().setValue("1")
self.performSegue(withIdentifier: "goHome", sender: self)
print("yes")
}
When I try to do this, it gives me an error called SIGABART which I believe is associated with not having segues connected properly.
Yet if I delete this line:
self.ref?.child(email).childByAutoId().setValue("1")
or change the email field to a random string like "test", it works fine and appears in Firebase.
If I remember correctly, you can't use symbol # in nodes names. It's first problem. You can do it another, I think better, way:
You need to create user to ref like:
/users/uid from created FIRUser.
You can do it with next steps:
For example, your registration page will have 3 UITextFields: userEmail, userLogin and userPassword.
// *1* Create user
FIRAuth.auth()!.createUser(withEmail: userEmail.text!,
password: userPassword.text!)
{ user, error in
if error == nil {
// *2* Then log him in
FIRAuth.auth()!.signIn(withEmail: self.userEmail.text!,
password: self.userPassword.text!)
{ result in
// *3* Create new user in database, not in FIRAuth
let uid = (FIRAuth.auth()?.currentUser?.uid)!
let ref = FIRDatabase.database().reference(withPath: "someStartPart/users").child(uid)
ref.setValue(["uid": uid, "email": userEmail.text!, "login": userLogin.text!, "creationDate": String(describing: Date())])
self.performSegue(withIdentifier: "fromRegistrationToMainPage", sender: self)
}
} else {
print("\(String(describing: error?.localizedDescription))")
}
}
Like this. Hope it helps.
Firebase Auth will not allow you to store such a value. You will need to save this into Firebase Database or another service. e.g. In the Firebase Database:
userRef.setValue("username123")
You should save the username value in the database. Something like this:
FIRdatabase.database().reference().child("yourchildname").updateChild(u)
(Im on my phone, so the call might not be EXACTLY like that, but should be very close)
Cheers.
Swift 4:
//***** for realTime database
let ref = Database.database().reference(fromURL: "https://add your project URL")
let userRef = ref.child("users").child(user.user.uid)
let values = ["Email": email, "UserName": userName] //userName is the name of textField

Resources