首页 > 解决方案 > 使用我的 swift 4 应用程序在 firebase 中保存 json 数组

问题描述

我有一个显示 4 个选项的应用程序。每天你点击一个或多个选项。现在,它像字符串数组一样存储在 firebase 数据库中,其中每个字符串都是选项之一。像这样

  override func addSelection(selection: String) {
self.quitPlan.medications.append(selection)
    }


    var medications: [String] {
        get {
            return document[Properties.medications.rawValue] as? [String] ?? []
        }

        set {
            document[Properties.medications.rawValue] = newValue
        }
    }

但我实际上想要一个带有选项和选项的json数组。我尝试过:

  override func addSelection(selection: String) {

        let medicationSelected = Medication(medication: selection, date: Date())
        self.quitPlan.medications.append(medicationSelected)

    }


    var medications: [Medication] {
        get {
            return document[Properties.medications.rawValue] as? [Medication] ?? []
        }

        set {
            document[Properties.medications.rawValue] = newValue
        }
    }


struct Medication {

    let medication: String
    let date: Date
}

但它不工作,我得到'FIRInvalidArgumentException', reason: 'Unsupported type: __SwiftValue'

标签: iosjsonswiftfirebase

解决方案


Firestore 可以将 Swift 结构保存到集合中,为此有一个模块。

首先,您应该包含模块:

import FirebaseFirestoreSwift

然后,只需执行以下操作:

db.collection("yourCollectionName").document(from: yourSwiftObject)

它将被转换为保存在您的 Firestore 集合中。


推荐阅读