【问题标题】:Firebase Firestore: Encoder from custom structs not workingFirebase Firestore:来自自定义结构的编码器不起作用
【发布时间】:2021-06-15 11:33:01
【问题描述】:

所以我创建了一个函数,我尝试在我的 Firestore 中创建一个存储用户数据的文档。但是当我的项目升级到 Xcode 13.0 beta 时,Firebase 编码器已经停止工作。其他人遇到类似问题吗?

我的模型如下所示:

struct User: Identifiable, Codable {
    
    @DocumentID var id: String?
    
    var auth_id: String?
    var username: String
    var email: String

    enum CodingKeys: String, CodingKey {
        case auth_id
        case username
        case email
    }
    
}

然后像这样调用 Firebase:

let newUser = User(auth_id: idToken, username: name, email: email)
            
try await databasemodel.database.collection("users").document(idToken).setData(newUser)

使用此代码创建的文档尚不存在,但该代码较早。 现在,当我编译时出现错误:“无法将'User'类型的值转换为预期的参数类型'[String:Any]'” 没有显示其他错误,我很确定其余代码按预期工作。

【问题讨论】:

    标签: swift google-cloud-firestore


    【解决方案1】:

    所以我在 Codables 上遇到了类似的问题...我做了这个小扩展来拯救我。也许它也适合你:)

    extension Encodable {
        /// Convenience function for object which adheres to Codable to compile the JSON
        func compile () -> [String:Any] {
            guard let data = try? JSONEncoder().encode(self) else {
                print("Couldn't encode the given object")
                preconditionFailure("Couldn't encode the given object")
            }
            return (try? JSONSerialization
                .jsonObject(with: data, options: .allowFragments))
                .flatMap { $0 as? [String: Any] }!
        }
    }
    

    你可以这样做

    try await databasemodel.database.collection("users").document(idToken).setData(newUser.compile())
    

    注意。我没有测试这个。我只是提供解决我遇到相同问题时的问题的扩展。

    【讨论】:

    • 好的,我终于有时间测试了,但我的 @DocumentID 值有问题。我想将它用作文档名称,但 JSON 编码器不允许这样做,我收到“encodingIsNotSupported”错误...
    猜你喜欢
    • 2012-12-10
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多