简体   繁体   中英

Firebase Firestore query not executing

func setExpenses(){
    FirebaseFunctions().retrieve(from: .expense, username: username as! String, returning: Expenses.self) { (expenses) in
        self.expenses = expenses
    }
}

I currently have a firebase query as seen above which retrieves a list of expenses from a cloud firestore database. However, when I run the function bellow and try and print the array, I get a result of the array being empty. I don't understand why the query isn't being able to execute correctly. I have the same code in another view controller, and it works fine which makes me think that it is something to do with the timing. But can somebody please help me to solve this issue?

public func getCollectionExpenses(collection: String, completionHandler: @escaping([[Expenses]], [String]) -> Void){
    setExpenses()
    print(expenses)
    print("hello")
    for eachExpense in expenses{
        if eachExpense.collection == collection{
            expensePerCollection.append(eachExpense)
        }
    }

Here is the code for the retrieve function, just in case

  func retrieve<T: Decodable>(from collectionReference:FIRCollectionReference, username:String, returning objectType: T.Type, completion: @escaping (([T]) -> Void)) {

    referenceSub(to: collectionReference, username: username).addSnapshotListener { (snapshot, _) in

        guard let snapshot = snapshot else { return }

        do {

            var objects = [T]()
            for document in snapshot.documents {
                let object = try document.decode(as: objectType.self)
                objects.append(object)
            }

            completion(objects)

        } catch {
            print(error)
        }
}
}

Where are you setting snapshot.documents ? Looks like you need to set in then iterate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM