简体   繁体   中英

Swift iOS -Is it Possible For Firebase to Corrupt Data and Return a Nil Value Even Though Valid Data Exists?

Before I send data to Firebase I make sure that a value definitely exists. At several different points throughout my app I pull that data from Firebase Database. Is there any chance that a mistake can be made while Firebase is retrieving that data and it returns nil instead of the actual data?

Basically can Firebase corrupt valid data and return it in the form of a nil value?

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

            if let dict = snapshot.value as? [String:Any]{

                //100% these have valid data
                //but if either of these get corrupted and returned as nil there will be a crash
                let firstName = dict["firstName"] as? String
                let lastName = dict["lastName"] as? String

                self.firstNameLabel.text! = firstName!
                self.lastNameLabel.text! = lastName!            
            }
}

I know I can use if let to prevent a crash but I want to know is it even necessary? I have way more data being pulled then firstName and lastName and I would have to use if let all over the place. Even though it's the safe thing to do it's adds a lot of code throughout my app. If unnecessary I won't use it.

if let firstName = firstName{....
if let lastName = lastName{....

This is my first time building an app, and I've never worked on or with a team before so I don't know the answer to a question like this.

No, when you retrieve values from Firebase you are sure you get the values from the database correctly, when the values are not in your cache . A common mistake I see here is that they have persistence on in there appDelegate, and they do not sync the database before capturing a singleEvent, like you are doing. When using childAdded, childRemoved etc, the database is always in sync, so you do not have to call keepSynched/turn persistence off.

Below code looks cleaner, safer and more understandable. I just added default values.

nameRef?.observeSingleEvent(of: .value, with: {
            (snapshot) in
                let values = snapshot.value as? NSDictionary
                self.firstNameLabel.text! = dict["firstName"] as? String ?? "No first name given"
                self.lastNameLabel.text! = dict["lastName"] as? String ?? "No last name given"
}

If you have persistence on in your appDelegate, call nameRef?.keepSynced(true) before capturing data with a observeSingleEvent. Not calling this can result in strange snapshot values, like this one: How to retrieve data from firebase using Swift?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM