在功能之外访问Firestore数据 [英] Accessing Firestore data outside of Function

查看:47
本文介绍了在功能之外访问Firestore数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 FirestoreService 文件中有一个FireStore函数,如下所示;

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
}

如何获取返回值以填充 viewController

how do I get returned values to populate my private var discounts = [Discount]() variable in my viewController

非常感谢,一如既往...

Many thanks as always...

推荐答案

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

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

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

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

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.

代码:

class ViewController: UIViewController {

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

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

}

这篇关于在功能之外访问Firestore数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆