如何将数组数据添加到Firebase实时数据库?

时间:2019-11-20 21:22:05

标签: ios swift database firebase firebase-realtime-database

我目前正在尝试使用SwiftUI和Firebase开发一个简单的ToDoList应用。该应用程序具有唯一的待办事项列表,对于每个待办事项列表,用户应该可以添加多个待办事项。我已经有一个类,用户可以用来创建新的待办事项列表,现在我想添加将待办事项添加到这些列表中的功能。

我已经拥有的POJO类:

import Foundation
import FirebaseDatabase

struct ToDoList: Identifiable {

    let ref: DatabaseReference?
    let key: String
    let todoName: String
    let priority: Int
    let type: String
    var dueDate = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
    let id: String

    init(todoName: String, priority: Int, type: String, dueDate: String, key: String = "") {
        self.ref = nil
        self.key = key
        self.todoName = todoName
        self.priority = priority
        self.type = type
        self.dueDate = dueDate
        self.id = key
    }

    init?(snapshot: DataSnapshot) {
        guard
            let value = snapshot.value as? [String: AnyObject],
            let todoName = value["todoName"] as? String,
            let priority = value["priority"] as? Int,
            let type = value["type"] as? String,
            let dueDate = value["dueDate"] as? String
            else {
                return nil
            }
        self.ref = snapshot.ref
        self.key = snapshot.key
        self.todoName = todoName
        self.priority = priority
        self.type = type
        self.dueDate = dueDate
        self.id = snapshot.key
    }

    func toAnyObject() -> Any {
        return [
            "todoName": todoName,
            "priority": priority,
            "type": type,
            "dueDate": dueDate
        ]
    }
}

我要显示在Firebase Realtime数据库中的结构如下:

Data structure in Firebase Console that I want to accomplish

如何更改我的POJO类以使该功能正常工作?

0 个答案:

没有答案