4

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.

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I'll look into those possibilities and let you know if I find a fix.
It did not, I still haven't found a solution. :( Once this project is more stable I'm going to try to isolate the issue and see if I can reproduce it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.