hvasam
hvasam

Reputation: 314

observeSingleEvent(of:with:) fetching old data

Background:

I have an app where new users complete a sign-up form (consisting of a username, email, and a password) to register for an account. When the new user submits the form, the app checks its Firebase Database to see if the username has already been taken. The problem here is that observeSingleEvent(of:with:) is not getting the newest data. When I update the data directly from the Firebase console, the changes are not reflected back in the returned results of observeSingleEvent(of:with:). Even between app restarts, the new data changes are not returned.

The only thing I've seen on the issue is here. A user says not to have persistence enabled when using observeSingleEvent(of:with:). But, I have persistence disabled. Also, I set the keepSynced() on the FIRDatabase instance to false (and I've tried true as well). No luck with either setting.

Here's an example of what I am trying:

let usersDatabaseReference = FIRDatabase.database().reference().child("users")
usersDatabaseReference.keepSynced(false)

// Query the database to see if the username is available 
// The user with the username "mark" was removed from the database via the Firebase console
let username = "mark" // This user used to exist in the database (and was previously added through the app).  
usersDatabaseReference.child(username).observeSingleEvent(of: .value, with: { (snapshot) in ... } )

The above code block should return the newest data (one where the user "mark" should not exist).

I am wondering if anyone else ran into this problem, or if anyone has possible solutions.

Note: Developing using iOS 10.1 and swift 3.

Upvotes: 6

Views: 760

Answers (3)

hvasam
hvasam

Reputation: 314

So, my problem had nothing to do with caching or fetching old results. Some of my code logic depended on checking the value of the snapshot parameter that was passed back in the completion handler for observeSingleEvent(of:with:). I wrongly assumed that I could check for a null database value by comparing it with nil; this led to a misinterpretation of results.

The best way to actually check for a null database fetch is by calling the exists() method on a FIRDataSnapshot instance. exists() returns true if the snapshot contains a non-null value.

Upvotes: 0

Oussema Aroua
Oussema Aroua

Reputation: 5339

the observeSingleEvent(of:with:) return the value only one time

try this :

refHandle = postRef.observe(FIRDataEventType.value, with: { (snapshot) in
  let postDict = snapshot.value as? [String : AnyObject] ?? [:]
  // ...
})

this will add a listener on database event link

Upvotes: 1

Paulo Mattos
Paulo Mattos

Reputation: 19339

I recommend you refactor your JSON data model using the username as key. Doing this, you should get an error when trying to create a duplicate user in the database.

Upvotes: 0

Related Questions