1

I have signed up using a SignUpViewController -

  import UIKit
  import Firebase
  import FirebaseFirestore
  import FirebaseAuth
 
   class SignUpViewController: UIViewController {

   @IBOutlet weak var firstNameTextField: UITextField!

   @IBOutlet weak var lastNameTextField: UITextField!

   @IBOutlet weak var emailTextField: UITextField!

   @IBOutlet weak var passwordTextField: UITextField!

   @IBOutlet weak var signUpButton: UIButton!

   @IBOutlet weak var errorLabel: UILabel!


   override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    setUpElements()
   }

   func setUpElements() {

    // Hide the error label
    errorLabel.alpha = 0

    // Style the elements
    Utilities.styleTextField(firstNameTextField)
    Utilities.styleTextField(lastNameTextField)
    Utilities.styleTextField(emailTextField)
    Utilities.styleTextField(passwordTextField)
    Utilities.styleFilledButton(signUpButton)
    }

   // Check the fields and validate that the data is correct. If everything is correct, this    method returns nil. Otherwise, it returns the error message
func validateFields() -> String? {
    
    // Check that all fields are filled in
    if firstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
        lastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
        emailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
        passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        
        return "Please fill in all fields."
    }
    
    // Check if the password is secure
    let cleanedPassword = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    
    if Utilities.isPasswordValid(cleanedPassword) == false {
        // Password isn't secure enough
        return "Please make sure your password is at least 8 characters, contains a special character and a number."
   
    
    
    
    
    
    }
    
    return nil
}
@IBAction func signUpTapped(_ sender: Any) {
    print("y")
    Analytics.logEvent(AnalyticsEventSignUp, parameters: nil)
    // Validate the fields
    let error = validateFields()
    
    if error != nil {
        
        // There's something wrong with the fields, show error message
        showError(error!)
    }
    else {
        
        // Create cleaned versions of the data
        let firstName = firstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        let lastName = lastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        // Create the user
       
        
        Auth.auth().createUser(withEmail: email, password: password) { authResult, error in

            
            // Check for errors
            if error != nil {
                
                // There was an error creating the user
                self.showError("Error creating user")
            }
            else {
                
                // User was created successfully, now store the first name and last name
                let db = Firestore.firestore()
                
                 db.collection("users").addDocument(data: ["email" : email, "firstname" :firstName, "lastname":lastName, "uid": authResult!.user.uid ])  { (error) in
                    
                    if error != nil {
                        // Show error message
                        self.showError("Error saving user data")
                    }
                }
                
                // Transition to the home screen
                self.transitionToHome()
            }
            
        }
        
        
        
    }
}

func showError(_ message:String) {
    
    errorLabel.text = message
    errorLabel.alpha = 1
}

func transitionToHome() {
    
    let homeViewController = storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController
    
    view.window?.rootViewController = homeViewController
    view.window?.makeKeyAndVisible()
    
    }

  }

The above SignUpViewController works fine and I signup (which automatically signsin) in the Firebase console as shown below -

enter image description here

Now, when I try to signout/logout using LoginViewController below, the firebase console does not bat an eyelid :-

  import UIKit
  import FirebaseAuth
  class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!



  override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    
    setUpElements()
 }

  func setUpElements() {
    
    // Hide the error label
    errorLabel.alpha = 0
    
    // Style the elements
    Utilities.styleTextField(emailTextField)
    Utilities.styleTextField(passwordTextField)
    Utilities.styleFilledButton(loginButton)
    
   }




     @IBAction func loginTapped(_ sender: Any) {
    
    // TODO: Validate Text Fields
    
    // Create cleaned versions of the text field
    let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    
    // Signing in the user
    Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
        
        if error != nil {
            // Couldn't sign in
            self.errorLabel.text = error!.localizedDescription
            self.errorLabel.alpha = 1
          }
         else {
            
            let homeViewController = self.storyboard?.instantiateViewController(identifier:  Constants.Storyboard.homeViewController) as? HomeViewController
            
            self.view.window?.rootViewController = homeViewController
            self.view.window?.makeKeyAndVisible()
           }
        }
     }

      @IBAction func logoutTapped(_ sender: Any){  let firebaseAuth = Auth.auth()
    do {
    print("button pressed")
    Auth.auth().addStateDidChangeListener { auth, user in
    if User.self as Any? != nil {
    print("User is signed in.")
        do {
           try firebaseAuth.signOut()
           } catch let signOutError as NSError {
           print ("Error signing out: %@", signOutError)
           }
       } else {
    print("User is signed out.")
      }
     }
    

   }
  }

 }

LoginViewController screenshot -

enter image description here

So, how to logout/signout from the firebase console ?

So, I have the following hiccups -

i)In LoginViewController - How to log-out/sign-out and also sign-back-in from LoginViewController in the firebase console ?

ii)In SignUpViewController - How to stop user from automatically signing in from SignUpViewController and make him/her sign-in through LoginViewController instead ? Also, in firestore, no collection "users" and documents "email", "firstname", "lastname". Do I have to add them manuallyl in Frestore ?

askit
  • 205
  • 4
  • 21
  • I wonder if the LoginViewController is working at all ? 'cause I have directly signed-in from the SignUpViewController. But there is not way to test untill I logout. Though, I have checked the connections, buttons also click on the simulator, deleted derived-data, clean-built folder, still no avail. – askit Mar 05 '21 at 12:17
  • Have you at least read the auth tutorial? https://firebase.google.com/docs/auth/ios/start And what is wrong with try! Auth.auth().signOut() ? – lajosdeme Mar 22 '21 at 16:45
  • I have also signed in successfully with using simulator, but it does not show in console. Login and logout does not work at all,though signup works. I wonder whether there is something wrong with settings ? – askit Mar 23 '21 at 14:36

6 Answers6

1

I used this method for LogOut from Firebase Login

[[GIDSignIn sharedInstance] signOut];

Use following code for login via Firebase Auth()

#import <FirebaseAuth/FirebaseAuth.h>
#import <GoogleSignIn/GoogleSignIn.h>

[GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID;
[GIDSignIn sharedInstance].delegate = self;

Step 1: Create Login method in AppDelegate

- (void)googleSignIN {
    [GIDSignIn sharedInstance].presentingViewController = self.window.rootViewController;
    [[GIDSignIn sharedInstance] signIn];
}

Step 2: Firebase SignIn Delegate Methods

- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
    if (error != nil) {
        if (error.code == kGIDSignInErrorCodeHasNoAuthInKeychain) {
            NSLog(@"The user has not signed in before or they have since signed out.");
        } else {
            NSLog(@"%@", error.localizedDescription);
        }
        return;
    }
    
    // Perform any operations on signed in user here.
    NSString *fullName = user.profile.name;
    NSString *email = user.profile.email;
    
    GIDAuthentication *authentication = user.authentication;
    FIRAuthCredential *credential =
    [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
                                     accessToken:authentication.accessToken];
    NSLog(@"User ID:%@",user.userID);
    [[FIRAuth auth] signInWithCredential:credential
                              completion:^(FIRAuthDataResult * _Nullable authResult,
                                           NSError * _Nullable error) {
        if (error) {
            // ...
            NSLog(@"Sign In Error%@", error.localizedDescription);
            return;
        }
        
        if (authResult == nil) { 
            NSLog(@"Authentication is Nil");
            return;
        }
        
        NSLog(@"Authentication %@",authResult.user.uid);
        
    }];
}
Parth Patel
  • 915
  • 11
  • 33
  • Are you sure you are using swift ? – askit Mar 19 '21 at 09:24
  • @askit Yes i m using but i have that code in Objective C. You can translate it via https://swiftify.com – Parth Patel Mar 21 '21 at 05:31
  • 1
    I am giving you +1 (upvote) because this answer somewhat helped me with this question:- https://stackoverflow.com/questions/67007397/swift-firebase-google-sign-in-not-showing-on-console – askit Jun 03 '21 at 05:34
1

Coming from the android background but signing out the user should be straight forward. Maybe try this

do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print ("Error signing out: %@", signOutError)
}
Zeeshan Shabbir
  • 6,704
  • 4
  • 38
  • 74
0
  • I use the below code for the sing out, this might you help.

    do{
      try Auth.auth().signOut()
      return true } catch {
      return false }
    
0
func logOut(){
        do {
            try Auth.auth().signOut()
            GIDSignIn.sharedInstance().signOut()
        
        } catch let signOutError as NSError {
            print ("Error signing out: %@", signOutError)
        }
    
    }
Amila
  • 244
  • 1
  • 12
  • "GIDSignIn" is used when users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app. As you can see in the image, I am not doing that right now, I am just creating my own random email id. and trying to logout and login again with that, which is not working. – askit Mar 18 '21 at 08:20
  • ok, let me try google signin as well, see how it goes..... – askit Mar 18 '21 at 08:32
0

This is from Firebase documentation: https://firebase.google.com/docs/auth/ios/custom-auth

Please try, it should work:

let firebaseAuth = Auth.auth()

do {
  try firebaseAuth.signOut()

} catch let signOutError as NSError {
  // handle the error here
  print ("Error signing out: %@", signOutError)
}

Adriatik Gashi
  • 332
  • 4
  • 10
0

I finally figured out, the Firebase Auth console does not show logout, it only shows login.

askit
  • 205
  • 4
  • 21