Accessing Firestore data outside of Function [duplicate]

走远了吗. 提交于 2021-01-29 11:42:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!