Swift Firebase在整个应用程序中重用一个功能

时间:2017-11-30 19:46:41

标签: swift function firebase google-cloud-firestore

在我的应用中,我在几个地方从Firebase Firestore数据库加载数据并显示数据。问题是我没有采用DRY技术而且我知道我不应该这样做,但我在我的应用程序的不同位置重复使用相同的加载功能。

func loadData() {

        let user = Auth.auth().currentUser
        db.collection("users").document((user?.uid)!).collection("children").getDocuments() {
            QuerySnapshot, error in
            if let error = error {
                print("\(error.localizedDescription)")
            } else {
                // get all children into an array
                self.childArray = QuerySnapshot!.documents.flatMap({Child(dictionary: $0.data())})
                DispatchQueue.main.async {
                    self.childrenTableView.reloadData()
                }
            }
        }
    }

该函数只是从数据库中抓取所有子项并将它们添加到我的子数组中。

有没有更好的方法来做这个或中心的地方我可以将这个功能放在可以被调用的地方,当我在应用程序中需要它而不是在多个视图控制器中重复添加它时?

我想过一个帮助器类,只是调用该函数,但是不知道如何将结果添加到我需要的viewcontroller中的childArray中?

我的孩子模特

import UIKit
import FirebaseFirestore


protocol DocumentSerializable {
    init?(dictionary:[String:Any])
}

// Child Struct
struct Child {

    var name: String
    var age: Int
    var timestamp: Date
    var imageURL: String

    var dictionary:[String:Any] {
        return [
            "name":name,
            "age":age,
            "timestamp":timestamp,
            "imageURL":imageURL
        ]
    }

}

//Child Extension
extension Child : DocumentSerializable {
    init?(dictionary: [String : Any]) {
        guard let  name = dictionary["name"] as? String,
            let age = dictionary["age"] as? Int,
            let  imageURL = dictionary["imageURL"] as? String,
            let timestamp = dictionary["timestamp"] as? Date else {
                return nil
        }
        self.init(name: name, age: age, timestamp: timestamp, imageURL: imageURL)
    }
}

1 个答案:

答案 0 :(得分:1)

编辑:我已更新以安全地打开选项。您可能仍需要修改,因为我不确定您的Firebase结构是什么,也不知道您的Child初始化程序。

您可以将其写为静态函数,然后在任何地方重复使用它。我假设你可能有一些与任何相关的课程#34;孩子"是,而且这是最好的实施地点。您可以在完成处理程序中传递结果(作为Child的选项数组),以便您可以使用这些结果执行所需的任何操作。它看起来像这样:

static func loadData(_ completion: (_ children: [Child]?)->()) {

    guard let user = Auth.auth().currentUser else { completion(nil); return }
    Firestore.firestore().collection("users").document(user.uid).collection("children").getDocuments() {
        querySnapshot, error in
        if let error = error {
            print("\(error.localizedDescription)")
            completion(nil)
        } else {
            guard let snapshot = querySnapshot else { completion(nil); return }
            // get all children into an array
            let children = snapshot.documents.flatMap({Child(dictionary: $0.data())})
            completion(children)
        }
    }
}

假设您在Child类中实现了这一点,您可以像这样使用它:

Child.loadData { (children) in
    DispatchQueue.main.async {
        if let loadedChildren = children {
            //Do whatever you need with the children
            self.childArray = loadedChildren
        }
    }
}