What if I have currentUser == nil in firebase while reauthenticateWithCredential iOS Swift - ios

Sometimes we get Auth.auth().currentUser as nil (May be when session for that login expires).
My main question is:
What is the reason behind currentUser being nil.
If the curentUser is nil what if I call the reauthenticateWithCredential method on it?
Do reAuthenticate method fills the session again and start providing values in the currentUser?
Below is the code to reAuthenticate user.
func authenticateUser()
{
let credential = EmailAuthProvider.credential(withEmail: myEmail, password: myPassword)
Auth.auth().currentUser?.reauthenticate(with: credential, completion: { (dataResult, error) in
if(error == nil){
print("Email login success")
completionHandler(true)
}else{
print("Email login failed - " + error.debugDescription)
completionHandler(false)
}
})
}
Any HELP will be Appreciated,
Many Thanks!!
Dinal J

Related

How to solve the problem with Firebase listener, which open everywhere?

I have some simple App, which have auth.
nearest code check if you already entered:
func signingManager(){
Auth.auth().addStateDidChangeListener { [weak self] (auth, user) in
guard let self = self else {return}
if user != nil {
self.showNextVC()
print("You are already entered")
}
}
}
It's works when you first open the app and if you entered func "showNextVC" will open next VC.
In the same time i have login button with code :
#IBAction func logInTapped(_ sender: UIButton) {
guard let email = emailTextField.text, let password = passwordTextField.text, email != "", password != "" else {
displayWarningLabel(withText: "info is incorrect")
return
}
Auth.auth().signIn(withEmail: email, password: password, completion: { [weak self] (user, error) in
if error != nil {
self?.displayWarningLabel(withText: "error occured")
return
}
if user != nil {
self?.showNextVC()
print("Congratulations, you have successfully logged in!")
}
self?.displayWarningLabel(withText: "no such user")
}
)}
Now about the problem: if I click the "login" button, the "signingManager ()" method and it's "showNextVC" are triggered first, and only then the "logInTapped" method itself and again "showNextVC".
As a result, I have 2 VCs and two messages:
"You are already entered" and
"Congratulations, you have successfully logged in!"
What am I doing wrong? Thanks!
Since you're listening for for auth state changes, you don't need to handle the self?.showNextVC() in the completion callback for signIn(withEmail:, password:). That code should only be present in the callback for addStateDidChangeListener.
Alternatively, you can:
Use the addStateDidChangeListener to initially detect whether the user is signed-in already.
Inside the callback for the state change:
Remove the listener by calling removeAuthStateDidChangeListener
Start the explicit sign-in flow, and call signIn(withEmail:, password:) like you're doing now.

Update Email using Phone Auth Credential iOS

I am creating an application which authenticate user using PhoneAuth. In my application I have a function which let user add Email to his account But not meant that I authenticate user using Email and Password, I just want to add email to his/her account (auth.auth().currentUser).
Initially, I let user to add his/her email in textfield and then I start to logout user from his/her device in order to reauthentication otherwise, I cannot update user's email using auth.updateEmail(). But sadly, the credential always expired after I called func updateEmail().
This is how I signIn user and update Email
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verficationID, verificationCode: code)
Auth.auth().signInAndRetrieveData(with: credential) { (result, error) in
guard let result = result else {
completion(false)
return
}
if error == nil {
guard let user = Auth.auth().currentUser else {
return
}
if UserDefaults.standard.getUserUpdatedEmail() {
user.reauthenticate(with: credential, completion: { (error) in
if error == nil {
user.updateEmail(to: newEmail, completion: { (error) in
if error == nil {
UserDefaults.standard.setUserUpdatedEmail(value: false)
completion(true)
//return true
} else {
completion(false)
//return false
print("Error validate email ",error?.localizedDescription ?? "")
}
})
} else {
completion(false)
// return false
print("Error reauthntication email ",error?.localizedDescription ?? "")
}
})
} else {
print("User is signed in \(result.user)")
print("This is userID \(result.user.uid)")
completion(true)
}
} else {
if let error = error {
print("Error during verification \(error.localizedDescription)")
}
completion(false)
}
}
I don't why the credential is expired too fast? I cannot figure it out how to update user email using PhoneAuthCredential. Is there any other techniques to do it?
You are trying to re-use the same phone credential (you used it first to sign-in). The phone credential is one time use only. If you want to update email immediately after sign-in, re-auth is not needed. However, if you try to update email after some time, you will need to send a new SMS code to re-authenticate.

Swift Firebase Auth Error

I'm currently working on an application with integrated Firebase login.
The last one I developed worked fine but the current App is causing a problem.
I'm taking the input from the Email and Password field and trying to login.
func login(user: String, pass: String){
Auth.auth().signIn(withEmail: user, password: pass) { (user, error) in
if(error != nil){
print("Success")
}
}
Every time I hit the "Login" button it prints "Success", even when I've not even entered Username and Password (blank text fields)
Code Snippet
Thanks for your Help in advance!
if (error != nil) ? Ok try to change if error == nil , because (error != nil) means that there is an error :).
func login(user: String, pass: String){
Auth.auth().signIn(withEmail: user, password: pass) { (user, error) in
if(error == nil){
print("Success")
} else {
print("error")
}
}

Firebase Auth always nil

I'm trying to Auth users with email but my function always return nil user. it worked perfectly until I added Facebook sign in as well, I made sure that I'm logged out of my facebook user when I try to register a new user to firebase.
Please let me know if any more of my code is needed to answer this.
Auth.auth().createUser(withEmail: email, password: pass, completion: {
(user, error) in
if user != nil {
print ("registered")
self.performSegue(withIdentifier: "goToHome", sender: self)
} else {
print("Error")
}
})
Instead of if user != nil do if (error != nil) and have your success code in the else statement.

Swift Facebook login with Firebase sdk is not working correctly

I'm developing app which uses Firebase.
I tried to login with facebook with firebase sdk but I can't catch event when user finishes authentication with facebook.
With my code, Nothing is printed.
Event print("checking") is not working.
let ref = Firebase(url: "https://nos.firebaseio.com/users")
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self, handler: {
(facebookResult, facebookError) -> Void in
print("checking")
if facebookError != nil {
print("Facebook login failed. Error \(facebookError)")
} else if facebookResult.isCancelled {
print("Facebook login was cancelled.")
} else {
let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
ref.authWithOAuthProvider("facebook", token: accessToken,
withCompletionBlock: { error, authData in
if error != nil {
print("Login failed. \(error)")
} else {
print("Logged in! \(authData)")
}
})
}
})
I'm using the latest version of xcode(7.2).
Is there anybody who has experience in this?
I'm looking for your answer.
I think there's a problem with your ref.
Try it without the /users
let ref = Firebase(url: "https://nos.firebaseio.com")
The rest of the login function works fine.

Resources