在功能之外访问Firestore数据

时间:2019-06-03 13:45:01

标签: swift google-cloud-firestore closures

我的FirestoreService文件中具有以下FireStore功能;

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
}

如何获取返回的值,以在private var discounts = [Discount]()中填充viewController变量

非常感谢……

1 个答案:

答案 0 :(得分:4)

您的函数将冻结您的UI,直到其操作完成。可能需要很长时间才能完成的功能应该使用转义闭包异步完成。该功能应如下所示:

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)
        }
    }
}

注意:如果出错,数据将返回空。如果需要,请处理错误情况。

我们首先需要一个FirestoreService类的实例。然后,该实例应调用retrieveDiscounts()函数并将其填充到我们的实例中,即折扣。

代码:

class ViewController: UIViewController {

    private var discounts = [Discount]() {
        didSet {
           self.tableView.reloadData()
        }
    }

    func viewDidLoad() {
       super.viewDidLoad()
       FirestoreService().retrieveDiscounts { discounts in
          self.discounts = discounts
       }
    }

}