Firebase: cannot retrieve children if they are less than the specified number in queryLimited

Viewed 106

I have the following function that gets invoked when a user scrolls conversation tableview, it works well but if the remaining children are less than the specified number it retrieves none! What is more interesting is that those values appear in print(snapshot.value) but not in print(child). How can I get all nodes even if they are less than the specified number?

Thank you.

func fetchBatch(betweenUser userID: String, fromTimestamp: Double , completion: @escaping([Message]) -> ()){
        guard let currentUID = Auth.auth().currentUser?.uid else { return }
        var messages = [Message]()
        REF_MESSAGES.child(currentUID).child(userID).queryOrdered(byChild: "timestamp").queryEnding(atValue: fromTimestamp).queryLimited(toLast: 20).observeSingleEvent(of: .value) { snapshot in
            print(snapshot.value)
            for child in snapshot.children {
                print(child)
                if let childSnapshot = child as? DataSnapshot {
                    guard let dictionary = childSnapshot.value as? [String: AnyObject] else {return}
                    let message = Message(dictionary: dictionary)
                    messages.append(message)
                }
            }
            return completion(messages)
        }
    }
1 Answers

Just a guess but you may have a problem with your data structure.

That guard statement

guard let dictionary = childSnapshot.value as? [String: AnyObject] else {return}

will prevent the messages array from being fully populated when it fails.

My guess is your retrieving say, 10 child notes, then as the code iterates over them, at some point the guard statement fails due to the structure. For example a [Int: Any] instead of a [String: Any]

The end result is that not all of the child nodes are not added to the array - which in turn means there's less elements in the array than was was actually retrieved from Firebase.

Related