gpt4 book ai didi

swift - 将 Codable 结构文档/数组插入/更新到 Firestore 的正确方法

转载 作者:行者123 更新时间:2023-12-05 03:54:33 25 4
gpt4 key购买 nike

我的 Firestore 文档结构,我是通过 Android 创建的:

--- Document
----- testA (object)
----- testB (array)
------- 0: Device item 1
------- 1: Device item 2

我有以下结构:

import Foundation
public struct Device: Codable {
var manufacturer: String?
var model: String?
var osVersion: String?

enum CodingKeys: String, CodingKey {
case manufacturer
case model
case osVersion
}
}

我的设备对象

let currentDevice = Device(manufacturer: "a", model: "b", osVersion: "c")

测试 A:将 Device 更新为 Document。我尝试了以下代码:

db.collection("testCollection").document("testDoc").updateData([testA: currentDevice])
...

测试 B:将 Device 添加到 testB 数组。

db.collection("testCollection").document("testDoc")
.updateData([testA: FieldValue.arrayUnion([currentDevice])])

这一切都导致以下错误:由于未捕获的异常“FIRInvalidArgumentException”而终止应用程序,原因:“不支持的类型:__SwiftValue”

我也查看了官方文档,但它并没有显示将结构对象更新到 Firestore。我能做什么?谢谢。

最佳答案

希望这能帮助到一些人。

首先,在上面的原始示例中,testA 没有被引用。字段键是一个字符串。应该是“testA”

为了使用 updateData 将项目保存到文档引用的数组中,需要将 swift 结构/类编码到字典中。 FirebaseFirestoreSwift 通过提供专门的编码器 来帮助解决这个问题。否则,您可以手动将您的结构转换为预期的 [String: Any] 字典。

此示例使用 FirebaseFirestoreSwift

        let currentDevice = Device(
manufacturer: "a",
model: "b",
osVersion: "c"
)
// declare outside of the try/catch block
let encoded: [String: Any]
do {
// encode the swift struct instance into a dictionary
// using the Firestore encoder
encoded = try Firestore.Encoder().encode(currentDevice)
} catch {
// encoding error
handleError(error)
return
}

let fieldKey = "testA"

// add a new item to the "testA" array.
db.collection("testCollection").document("testDoc")
.updateData(
[
fieldKey: FieldValue.arrayUnion([encoded])
]
) { error in
guard let error = error else {
// no error, that's great
return
}

// uh oh, firestore error
handleError(error)
return

}

关于swift - 将 Codable 结构文档/数组插入/更新到 Firestore 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60843811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com