Niall Kiddle
Niall Kiddle

Reputation: 1487

Firebase fetch user data - Swift

I want to fetch data, I have done this multiple times but for some reason it is not working and I see no reason as to why.

My code for fetching the data

func fetchCurrentUserInfo() {

    let currentUser = Auth.auth().currentUser!
    let currentUserRef = dataBaseRef.child("users").child(currentUser.uid)

    currentUserRef.observeSingleEvent(of: .value, with: { (snapshot) in

        let user = UserClass(snapshot: snapshot)
        self.downloadImageFromFirebase(urlString: user.photoURL!)
        self.userName.text = user.getFullName()

        //SD Cache
        self.userProfileImage.sd_setImage(with: URL(string: user.photoURL!), placeholderImage: UIImage(named: "UserImageTemplate"))

    }) { (error) in
        let alert = SCLAlertView()
        _ = alert.showError("OOPS!", subTitle: error.localizedDescription)
    }
}

My user class file

struct UserClass {

        var firstName: String?
        var email: String?
        var photoURL: String?
        var uid: String?
        var ref: DatabaseReference!
        var key: String?
        var lastName: String?
        var accountType: String?

        init(snapshot: DataSnapshot){

            key = snapshot.key
            ref = snapshot.ref
            accountType = (snapshot.value! as! NSDictionary)["Account Type"] as? String
            firstName = (snapshot.value! as! NSDictionary)["First Name"] as? String
            email = (snapshot.value! as! NSDictionary)["email"] as? String
            uid = (snapshot.value! as! NSDictionary)["uid"] as? String
            photoURL = (snapshot.value! as! NSDictionary)["photoURL"] as? String
            lastName = (snapshot.value! as! NSDictionary)["Last Name"] as? String
        }

        func getFullName() -> String {
            return ("\(firstName!) \(lastName!)")
        }

    }
}

I have set the read and write rules to true. When I call the fetchCurrentUserInfo function, it returns all the data for the first name, last name, key, etc. but it returns the photo URL, UID or email as nil giving me the error: fatal error: unexpectedly found nil while unwrapping an Optional value.

Upvotes: 0

Views: 595

Answers (1)

Glenn Posadas
Glenn Posadas

Reputation: 13281

Your crash log says it all. You're trying to force unwrap an optional variable by as! casting. Make sure you have valid values in your snapshot.

Also, a better model would like so, this is safer:

    struct UserClass {

        var firstName: String!
        var email: String!
        var photoURL: String!
        var uid: String!
        var ref: DatabaseReference!
        var key: String!
        var lastName: String!
        var accountType: String!

        init?(snapshot: DataSnapshot?) {

            guard let value = snapshot?.value as? [String: AnyObject],
                let accountType = value["Account Type"] as? String,
                let firstName = value["First Name"] as? String,
                let email = value["email"] as? String,
                let uid = value["uid"] as? String,
                let photoURL = value["photoURL"] as? String,
                let lastName = value["Last Name"] as? String else {
                    return nil
            }

            self.key = snapshot?.key
            self.ref = snapshot?.ref
            self.accountType = accountType
            self.firstName = firstName
            self.email = email
            self.uid = uid
            self.photoURL = photoURL
            self.lastName = lastName
        }

        func getFullName() -> String {
            return ("\(firstName!) \(lastName!)")
        }

    }

Upvotes: 2

Related Questions