Firebase Query Error Handling
firebase, firebase-realtime-database, ios, swift
Solution
There can be three possible errors that you might face while observing your database :-
- You haven't defined a proper path to your database `observe` query
- You are parsing in a wrong or faulty manner
- You don't have the permission to access that particular node at that particular time(Security Rules)
For the first two you have to take care of it yourself, But for the third condition you can use withCancel block:-
FIRDatabase.database().reference().child("users").queryOrderedByKey().queryEqual(toValue: "uid").observe(.childAdded, with: { (snapshot) in
//your code
}, withCancel: {(err) in
print(err) //The cancelBlock will be called if you will no longer receive new events due to no longer having permission.
})
- As far as error handling if the user looses network connection while Writing, Your app remains responsive regardless of network latency or connectivity. See the Write data offline section of Firebase Docs
Problem
I've got some functions to read data from Firebase, but sometimes I never get a response (or it's massively delayed). I read here that maybe Firebase can close the socket connection before data is received. It looks like someone had a similar issue here, but never posted a solution. Here's a sample of my code for downloading user data from Firebase. ``` // loads the current user's information static func loadUserDataWithCompletion(completion: (UserInfo) -> Void) { let ref = FIRDatabase.database().reference() print("loading current user data...") let uid = (FIRAuth.auth()?.currentUser?.uid)! ref.child("users").queryOrderedByKey().queryEqualToValue(uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in print("found user data!") if let dictionary = snapshot.value as? [String:AnyObject] { let info = userFromDict(dictionary) // execute code slated for completion completion(info) } }) } ``` Is there some way I can detect errors using `observeEventType`? Maybe then I'd at least get more information about why the issue is happening.