I am using firestore to query a document with data stored in a dictionary. I want to be able to traverse through each document, with the press of a IBAction UIButton and the function will also be incrementing the for-in loop count.
func queryMethod(){
let typeRef = Global.db.collection("userData")
let query = typeRef.whereField("type", isEqualTo: "Mentor")
query.getDocuments { querySnapshot, err in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
}
CodePudding user response:
Fetch the documents and store them into a constant property. Have a counter index variable that will be used as a subscript to access each item in your documents instead of using a for loop since you want to have control with accessing each document on a button click. So in your IBAction on click you can access each element like this:
if let document = querySnapshot!.documents[index] {
print("\(document.documentID) => \(document.data())")
}
index = 1
however you are going to access the items via subscript just make sure to handle array out of bounds situation in case your docs is an empty collection. You can add a check in the IBAction such that your index is less than the querySnapshot!.documents
-> perform the action.
if index < querySnapshot?.documents.count {
// access it via subscript of index value
}