【问题标题】:Accessing Firestore data outside of Function [duplicate]在函数之外访问 Firestore 数据 [重复]
【发布时间】:2019-06-03 13:45:01
【问题描述】:

我的 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
}

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

非常感谢一如既往...

【问题讨论】:

标签: swift google-cloud-firestore closures


【解决方案1】:

您的函数将使您的 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
       }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2017-05-24
    • 2020-02-24
    • 1970-01-01
    • 2020-07-14
    相关资源
    最近更新 更多