如何从Firestore返回数组中的数据?

时间:2019-07-25 01:51:01

标签: ios swift firebase google-cloud-firestore read-data

我正在构建一个IOS应用程序,我正处于要在pickerview中加载某些类别的阶段。类别列表作为文档存储在Firestore中。

我有一个执行以下操作的函数:

  1. 启动数组
  2. 从Firestore读取数据
  3. 在数组上附加值
  4. 返回数组

问题是该函数似乎返回数组,甚至没有从Firestore获得任何结果

我的数据模型

class categoryModel {
    var catImg=""
    var catName=""
    var catID=""
    //set categories
    init(catImg: String, catName:String, catID:String){
        self.catName=catName
        self.catImg=catImg
        self.catID=catID
    }
}

Firestore参考

struct FirestoreReferenceManager {

    static let event = "events"

    static let db = Firestore.firestore()
    static let rootEvents = db.collection("events")
    static let rootUsers = db.collection("users")

}

Firestore服务

class FirestoreService {

    static func getCategoryfromDB()->[categoryModel] {

        let rootCategory = FirestoreReferenceManager.rootEvents
        var tabCategory=[categoryModel]()


        rootCategory.getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {

                    tabCategory.append(categoryModel(catImg: document.data()["img"] as! String, catName:document.data()["name"] as! String, catID: document.documentID))

                    print("number of categories running: \(tabCategory.count)")
                }
            }

        }
        print("number of categories final: \(tabCategory.count)")
        return tabCategory
    }
}

检查日志显示的内容

umber of categories final: 0
number of categories final: 0
number of categories running: 1
number of categories running: 2
number of categories running: 3
number of categories running: 4
number of categories running: 5
number of categories running: 6
number of categories running: 7
number of categories running: 8
number of categories running: 9
number of categories running: 10
number of categories running: 11
number of categories running: 1
number of categories running: 2
number of categories running: 3
number of categories running: 4
number of categories running: 5
number of categories running: 6
number of categories running: 7
number of categories running: 8
number of categories running: 9
number of categories running: 10
number of categories running: 11

第二行实际上应该是最后一行。

当我从ViewController读取Firestore时,该数组为空。我尝试对数据模型进行硬编码,并且可以正常工作。

我在获取数据时读到一些“延迟”,但是该如何解决呢?

我该如何解决问题?

3 个答案:

答案 0 :(得分:2)

类似的事情应该可以做到。 分发是可以向其中添加闭包的组。所有这些完成后,将调用notify闭包,您可以在其中返回数据。 阅读调度组,这将有所帮助。

static func getCategoryfromDB(completed: @escaping ([categoryModel]) -> Void) {

        let rootCategory = FirestoreReferenceManager.rootEvents
        var tabCategory=[categoryModel]()
        let dispatch = DispatchGroup()
        dispatch.enter()
        rootCategory.getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {

                    tabCategory.append(categoryModel(catImg: document.data()["img"] as! String, catName:document.data()["name"] as! String, catID: document.documentID))

                    print("number of categories running: \(tabCategory.count)")
                }
            }
            dispatch.leave()

        }
        dispatchGroup.notify(queue: .main, execute: {
            print("number of categories final: \(tabCategory.count)")
            completed(tabCategory)

        })


        }

答案 1 :(得分:0)

您似乎在代码的 asynchrony 中遇到了问题。

您的函数在实际运行文档的方括号中包含的代码实际运行之前调用return tabCategory

在异步过程完成后,使用转义闭包来调用函数。

您的成品看起来像这样:

static func getCategoryfromDB(completed: @escaping (([categoryModel]?, Error?)) -> Void) {

    let rootCategory = FirestoreReferenceManager.rootEvents

    rootCategory.getDocuments() { (querySnapshot, err) in
        if let err = err {
            tabCategory(nil, err)
        } else {
            var tabCategory=[categoryModel]()
            for document in querySnapshot!.documents {

                tabCategory.append(categoryModel(catImg: document.data()["img"] as! String, catName:document.data()["name"] as! String, catID: document.documentID))

                print("number of categories running: \(tabCategory.count)")
            }
          gotData(tabCategory, nil)
        }
    }
}

答案 2 :(得分:0)

由于@arvidure和其他人,我设法使下面的代码有效

我的数据模型

class categoryModel {
    var catImg=""
    var catName=""
    var catID=""
    //set categories
    init(catImg: String, catName:String, catID:String){
        self.catName=catName
        self.catImg=catImg
        self.catID=catID
    }
}

Firestore参考

struct FirestoreReferenceManager {

    static let event = "events"

    static let db = Firestore.firestore()
    static let rootEvents = db.collection("events")
    static let rootUsers = db.collection("users")

}

Firestore服务

class FirestoreService {

    static func getCategoryfromDB(dispatch:DispatchGroup, completed: @escaping ([categoryModel]) -> Void) {

        let rootCategory = FirestoreReferenceManager.rootEvents
        var tabCategory=[categoryModel]()
        //let dispatch = DispatchGroup()

        dispatch.enter()

        rootCategory.getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {

                    tabCategory.append(categoryModel(catImg: document.data()["img"] as! String, catName:document.data()["name"] as! String, catID: document.documentID))

                    print("number of categories running: \(tabCategory.count)")
                }
            }  
            dispatch.leave()
        }

        dispatch.notify(queue: .main, execute: {
            print("number of categories : \(tabCategory.count)")
            completed(tabCategory)

        })

    }
}

这就是我在viewcontroller中的称呼方式

super.viewDidLoad()

        let dispatch = DispatchGroup()
        category=CategoryModelPicker()
        //category.modelCategory=categoryData.getCategory()
        //category.modelCategory=FirestoreService.getCategoryfromDB(completed: category?.modelCategory)
        FirestoreService.getCategoryfromDB(dispatch:dispatch){(cat) in
            dispatch.notify(queue: .main, execute: {
                print("number of categories final: \(cat.count)")
                self.category.modelCategory=cat

                //Additional code

            })
        }
}

感谢您的帮助:)