问题
I have a FireStore function in my FirestoreService
file as below;
func retrieveDiscounts() -> [Discount] {
var discounts = [Discount]()
reference(to: .discounts).getDocuments { (snapshots, error) in
if error != nil {
print(error as Any)
return
} else {
guard let snapshot = snapshots else { return }
discounts = snapshot.documents.compactMap({Discount(dictionary: $0.data())})
}
}
return discounts
}
how do I get returned values to populate my private var discounts = [Discount]()
variable in my viewController
Many thanks as always...
回答1:
Your functions will get your UI to freeze until its operation is complete. The function which may take long duration to complete should be done asyncronous using escaping closures. The function should be like below :
func retrieveDiscounts(success: @escaping([Discount]) -> ()) {
var discounts = [Discount]()
reference(to: .discounts).getDocuments { (snapshots, error) in
if error != nil {
print(error as Any)
success([])
return
} else {
guard let snapshot = snapshots else { return }
discounts = snapshot.documents.compactMap({Discount(dictionary: $0.data())})
success(discounts)
}
}
}
Note: The data returns empty if error. Please handle error case if you need.
We first need an instance of FirestoreService class. Then the instance should call the retrieveDiscounts() function and populate it to our instance i.e. discounts.
Code:
class ViewController: UIViewController {
private var discounts = [Discount]() {
didSet {
self.tableView.reloadData()
}
}
func viewDidLoad() {
super.viewDidLoad()
FirestoreService().retrieveDiscounts { discounts in
self.discounts = discounts
}
}
}
来源:https://stackoverflow.com/questions/56428666/accessing-firestore-data-outside-of-function