Having an error following the 'Firebase Authentication Tutorial 2020'

Hi,

I have followed the Firebase Authentication Tutorial for a Custom iOS login page. The ‘Sign Up’ part is working, but whenever I select the ‘login’ button (in the ‘ViewController’ file) from the Simulator I get the following error come up.

Exception NSException * "[<iSelling.LoginViewController 0x7ff1d6d0c2d0> setValue:forUndefinedKey:]: this class is not key v

This is the code I currently have on the ViewController file for the Login button, exactly the same code as the Sign Up button (apart from names of course) but this one doesn’t work.

@IBOutlet weak var loginButton: UIButton!

Any ideas why it isn’t working properly? Is it just a dodgy xcode simulator or is there a bigger problem?

Hi Harry,

That error generally means that there is a broken connection from the storyboard View Controller to the relevant .swift file. In your case it may be that there is a connection broken between the LoginViewController in the storyboard and the LoginViewController.swift file.

Check that all the connections are active as per the red arrows in the attached images.


If you don’t see a filled in circle in the LoginViewController.swift file (denotes the connection is active) then you will have to recreate the connection.

Hi @Chris_Parker ,

I’ve attached a screenshot outlining that I have these filled in circles, which outline that the connection is active.

For some reason it still isn’t working :frowning:

Check that the segue is correctly set up between the login Button and the LoginViewController. If you select the segue in your storyboard, it should highlight the button that it is connected to.

Also check that the LoginViewController that you have configured in your Storyboard has the custom class added. Select the ViewController in your storyboard (circled) and then in the Identity Inspector make sure that the Custom Class is populated.

If I remove that class and run the project on my simulator, this is the error I receive:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7f9b9cd23e40> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key emailTextField.'

Hi @Chris_Parker,

Appreciate your help here, I had a dodgy connection which I removed, and I’ve now got it working!!!

When I log in, it says ‘welcome’ (label), how would I take the users first name and display “Welcome, Harry” or “Welcome, Chris” etc.??

Thank you so much for your help :slight_smile:

Is that label on the HomeViewController? Mine is different because I have been messing around with Firebase so the code is completely different to what Chris Ching had in his tutorial.

Yes I currently have a ‘Welcome’ label on the HomeViewController, I think there might be a Firebase function which lets you do this?

You would have to add code to your HomeViewController to read the “user” record from Firebase and populate the label accordingly based on what was stored when the user initially signed up.

What does your signUpTapped() code look like in your SignUpViewController?

I modified mine as an exercise and added a whole lot more fields.

Hi,

I have no idea how I’d go about doing that? This is the code for my signUpTapped()

{

    // 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) { (result, err) in
            
            // Check for errors
            if err != 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: ["firstname":firstName, "lastname":lastName, "uid": result!.user.uid ]) { (error) in
                    
                    if error != nil {
                        // Show error message
                        self.showError("Error saving user data")
                    }
                }
                
                // Transition to the home screen
                self.transitionToHome()
            }
            
        }
        
        
        
    }
}

In that code the “user” entry is created in the database with “firstname”, “last name” and “uid” so if you go and have a look at your Firebase console for that project and then select Cloud Firestore just below the Authentication option, you should see your “users” collection. Each user should have their firstname, lastname and uid as database fields.

To show the name of the user on the screen in the way that you were describing, the first thing to do is create an IBOutlet from your Storyboard HomeViewController to your HomeViewController.swift file. Create that by placing your project in Assistant Editor mode and drag the Label from your storyboard over to the HomeViewController.swift file to just above didLoadView() and name it. Maybe welcomeLabel, for example.

You now need to add code to read the database “users” records and pick out the one that matches the user who has just Signed On or Logged On looking for a matching “uid”

This is what you will have to place in your viewDidLoad() function to retrieve the name of the currentUser.

        let db = Firestore.firestore()
        let user = Auth.auth().currentUser

        db.collection("users").getDocuments { (snapshot, error) in
            if let error = error {
                print(error)
                return
            } else {
                for document in snapshot!.documents {
                    let data = document.data()
                    let userId = data["uid"] as! String
                    if userId == user?.uid {
                        let firstName = data["firstname"] as! String
                        self.welcomeLabel.text = "Welcome \(firstName)"
                    }
                }
            }
        }
1 Like

Hi Chris,

I have successfully linked the label to the text and added in the code sample above but nothing comes up on my app after I log in, and I get the following error (also added in the label to show you that it has been linked in problem)

Here’s how my label looks on the HomeViewController

Can you show a screen shot of your Cloud Firestore “user” collection from your Firebase console?

1 Like

Sure, here it is

Is there a uid field in every case for all the users created? I’m trying to figure out why you got that error so given that you have lots of records I wonder if any of them have a null uid field as that would account for the “unexpectedly found nil while unwrapping an optional value”

1 Like

Yes there is one - here

I mean in the “users” collection data in Cloud Firestore. Maybe one of the records has a null “uid”.

1 Like

Hi,

I went through and deleted all of the values in the ‘Authentication’ section, and the ‘Cloud Firestore’ section and tried to add a new account from scratch.

I logged in and it’s successfully working now!! I have absolutely no idea why it wasn’t working before, but for some reason it is now. Any idea how I can now keep the user logged in between sessions?

Thanks :slight_smile:

Hi Harry,

Well that’s good news.

In the Photo App, which is part of the iOS Database course, Chris Ching covers how to save the currently logged in user to User Defaults. When the App is opened some time later, the user is effectively still logged in.

1 Like

Thanks Chris, really appreciate your help!

Do you have paypal so I can buy you a ‘e-coffee’ to say thanks?