sharedev
sharedev

Reputation: 419

Despite multiple unwrapping attempts, fatal error: unexpectedly found nil while unwrapping an Optional value

I have been practicing a login page and the creation of an account with Firebase. I am successfully signing up a user and saving the user in firebase. Now I am trying to save a first and last name to the user id when they create their account. I've tried looking at other SO answers, but still can't seem to get this to work.

I have been going through multiple tutorials, and have tried multiple unwrapping attempts, but keep running into this error. Below is my view controller:

View Controller

import UIKit
import Firebase

class ViewController: UIViewController {
    var ref: DatabaseReference!

    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var firstNameField: UITextField!
    @IBOutlet weak var lastNameField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        var ref = Database.database().reference()
    }

    @IBAction func createAccountTapped(_ sender: Any) {
        if let email = emailTextField.text, let password = passwordTextField.text, let firstName = firstNameField.text, let lastName = lastNameField.text {
            Auth.auth().createUser(withEmail: email, password: password ) { (user, error) in
                // ...

                if let firebaseError = error {
                    print(firebaseError.localizedDescription)
                    return
                //add popup later
                }


                let userId = user!.uid
                self.ref.child("users").child(userId).setValue(["firstName": firstName])
                print("User registered in Firebase with a userId of " + user!.uid)

                }
        }
    }

Where am I going wrong? I thought I was unwrapping the variables at the top, with my 'if let'. I tried force unwrapping them individually, as well, but keep having the same error. A bit lost.

Upvotes: 0

Views: 138

Answers (2)

Siyavash
Siyavash

Reputation: 980

Please change your Database reference from

 var ref: DatabaseReference!

to

 var databaseRef = Database.database().reference()

and then do

 self.child("users").child(userId).setValue(["firstName": firstName])

or in you viewDidLoad do

self.ref = Database.database().reference()

This error happens because you are not initialising your Database reference

This should work without any problems

import UIKit
import Firebase
import FirebaseDatabase

class ViewController: UIViewController {
    var ref: DatabaseReference!

    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var firstNameField: UITextField!
    @IBOutlet weak var lastNameField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.ref = Database.database().reference()
    }

    @IBAction func createAccountTapped(_ sender: Any) {
        if let email = emailTextField.text, let password = passwordTextField.text, let firstName = firstNameField.text, let lastName = lastNameField.text {
            Auth.auth().createUser(withEmail: email, password: password ) { (user, error) in
                // ...

                if let firebaseError = error {
                    print(firebaseError.localizedDescription)
                    return
                //add popup later
                }


                let userId = user!.uid
                self.ref.child("users").child(userId).setValue(["firstName": firstName])
                print("User registered in Firebase with a userId of " + user!.uid)

                }
        }
    }

Upvotes: 2

Jen Person
Jen Person

Reputation: 7546

in viewDidLoad(), you call

var ref = Database.database().reference()

but it should be

ref = Database.database().reference()

Swift is treating it like a different variable that you're declaring within the scope of viewDidLoad(), so when you go to use ref, it still has no value.

Upvotes: 4

Related Questions