So my goal is to have purchased events show certain buttons when the detailsVC of the tableview cell loads and the non-purchased events show a different button. So what I did in this situation was do a query call to the documents in a collection path with the field purchased
: true
, and that if there was an error, handle it, but if there wasn't, show the buttons for the purchased events.
override func viewDidLoad() {
super.viewDidLoad()
viewPurchaseButton.isHidden = true
cancelPurchaseButton.isHidden = true
getSchoolDocumentID { (id) in
if let ident = id {
self.db.collection("school_users/\(ident)/events").whereField("purchased", isEqualTo: true).getDocuments { (querySnapshot, error) in
if let error = error {
print("There was an error fetching the docs: \(error)")
} else {
self.viewPurchaseButton.isHidden = false
self.cancelPurchaseButton.isHidden = false
self.purchaseTicketButton.isHidden = true
self.creditCard.isHidden = true
}
}
}
}
So I ran this thinking it would work, I only have 1 document out of 4 in the collection that has the field purchased
equal to true
, so i expected when I clicked on the cell with that field being true
in my tableVC, the details VC would display the proper buttons. The detailsVC displayed the proper buttons, but when i left the VC and clicked another cell that had the purchased
field as false
, I was quite confused to why the buttons were showing up. If anybody can explain to me why that happens or point out an issue with my code that would be great.
Ok so what I did for this to work was refactor the query, instead of getting documents, just get a single doc. I then used this function and it works like beauty! :)
override func viewDidLoad() {
super.viewDidLoad()
viewPurchaseButton.isHidden = true
cancelPurchaseButton.isHidden = true
getSchoolDocumentID { (schoolDocID) in
if let schID = schoolDocID {
self.db.document("school_users/\(schID)/events/\(self.selectedEventID!)").getDocument { (documentSnapshot, error) in
if let error = error {
print("There was an error fetching the document: \(error)")
} else {
guard let docSnap = documentSnapshot!.get("purchased") else {
return
}
if docSnap as! Bool == true {
self.viewPurchaseButton.isHidden = false
self.cancelPurchaseButton.isHidden = false
self.creditCard.isHidden = true
self.purchaseTicketButton.isHidden = true
} else {
self.creditCard.isHidden = false
self.purchaseTicketButton.isHidden = false
}
}
}
}
}
This gets the job done perfectly.