如何在 Swift 5 中将文档转换为自定义对象? [英] How to convert document to a custom object in Swift 5?
问题描述
我一直在尝试将从 Firebase 的 Cloud Firestore 检索到的文档转换为 Swift 5 中的自定义对象.我正在关注文档:
I've been trying to convert the document retrieved from the Firebase's Cloud Firestore to a custom object in Swift 5. I'm following the documentation:
但是,Xcode 向我显示了错误 Value of type 'NSObject' has no member 'data'
对于该行 try $0.data(as: JStoreUser.self)
.我已将结构定义为 Codable
.
However, Xcode shows me the error Value of type 'NSObject' has no member 'data'
for the line try $0.data(as: JStoreUser.self)
. I've defined the struct as Codable
.
代码:
func getJStoreUserFromDB() {
db = Firestore.firestore()
let user = Auth.auth().currentUser
db.collection("users").document((user?.email)!).getDocument() {
(document, error) in
let result = Result {
try document.flatMap {
try $0.data(as: JStoreUser.self)
}
}
}
}
用户结构:
public struct JStoreUser: Codable {
let fullName: String
let whatsApp: Bool
let phoneNumber: String
let email: String
let creationDate: Date?
}
截图:
有人知道如何解决这个问题吗?
Does anyone know how to resolve this?
推荐答案
在联系 firebase 团队后,我找到了我正在寻找的解决方案.事实证明,我必须显式地执行 import FirebaseFirestoreSwift
而不是只执行 import Firebase
.此后错误将消失.(当然,您需要先将 pod 添加到您的 podfile 中:D)
After contacting the firebase team, I found the solution I was looking for. It turns out I have to do import FirebaseFirestoreSwift
explicitly instead of just doing import Firebase
. The error will disappear after this. (And of course you'll need to add the pod to your podfile first:D)
这篇关于如何在 Swift 5 中将文档转换为自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!