Nicola Innocenti
Nicola Innocenti

Reputation: 31

Firebase iOS .queryOrderedByChild and .queryEqualTo not working

I'm trying to filter results from a Firebase database with a structure like this one.

chats
    chatId
        messages
            messageId
                userId: true

I need two queries, one that returns only messages with existing child userId (if it exists it will always be true), the other that returns only messages without it.

I'm trying with this two references and observing .childAdded event:

let messagesWithUser = FIRDatabase.database().reference(withPath: "chats").child(chat.id).child("messages").queryOrdered(byChild: userId).queryEqual(toValue: true).ref
let messagesWithoutUser = FIRDatabase.database().reference(withPath: "chats").child(chat.id).child("messages").queryOrdered(byChild: userId).queryEqual(toValue: NSNull()).ref

Currently the .childAdded event returns all messages without filtering.

Upvotes: 0

Views: 540

Answers (3)

Dmitriy Groschovskiy
Dmitriy Groschovskiy

Reputation: 153

Thank you Nicola. I need implement previous method into my function, but blueRewardBalance request parameters.

func blueRewardTransaction(purchaseValue: Double) {
        let newBalance = blueRewardBalance(completeBlock: //what I need paste here?) - purchaseValue
        let userRef = FIRAuth.auth()?.currentUser?.uid
        let firebaseRef = FIRDatabase.database().reference()
        firebaseRef.child("Reward/\(userRef!)").updateChildValues(["rewardCardBalance": newBalance])
    }

Upvotes: 0

Nicola Innocenti
Nicola Innocenti

Reputation: 31

In response to Dmitriy:

func blueRewardBalance(completeBlock: (value: Double) -> Void) {
        let userRef = FIRAuth.auth()?.currentUser?.uid
        var rewardBalance : Double! = 0.00
        let purchaseRef = FIRDatabase.database().reference(withPath: "Reward/\(userRef!)")
        purchaseRef.queryOrdered(byChild: "abc").observe(.value, with: { snapshot in
            let dataSnapshot = snapshot.value as! [String: AnyObject]
            rewardBalance = dataSnapshot["rewardCardBalance"] as! Double!
            completeBlock(rewardBalance)
        })
}

Upvotes: 3

Nicola Innocenti
Nicola Innocenti

Reputation: 31

Found out the problem. I was using FIRDatabaseReference instead of FIRDatabaseQuery to observe changes...

Upvotes: 0

Related Questions