Search code examples
iosfirebasegoogle-cloud-firestoreswift4querying

How to process firestore query as i am getting snapshot result as FIRQuerySnapshot`


I am facing problem while processing firestore query as my code is here

let wallpaperRef = Firestore.firestore().collection("wallpaper").order(by: "noOfDownloads", descending: true)

wallpaperRef.getDocuments(completion: { (snap, error) in
    if error == nil {
        print(snap)
    }

})

now the output of this query is this

Optional(<FIRQuerySnapshot: 0x600000070640>)
Optional(<FIRQuerySnapshot: 0x600000070640>)
Optional(<FIRQuerySnapshot: 0x6000000705c0>)

i want to take this querysnap and get data whatever is init to readable form


Solution

  • If you run a query against a collection, the result you get is a QuerySnapshot that contains (possibly) multiple documents. To get each document, you need to loop over the results. From the Firebase documentation on reading multiple documents:

    db.collection("cities").whereField("capital", isEqualTo: true)
        .getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")
                }
            }
    }
    

    So your code is jut missing the loop from that else block. Something like:

    wallpaperRef.getDocuments(completion: { (snap, error) in
        if error == nil {
            print(snap)
        } else {
            for document in snap!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
    })