Firebase (Cloud Firestore) - How to convert document to a custom object in Swift 5?

半世苍凉 提交于 2020-01-14 19:24:42

问题


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: https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects). 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. Does anyone know how to resolve this? Thanks!

The code:

    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)
                }
            }
        }

    }

The user struct:

public struct JStoreUser: Codable {
    let fullName: String
    let whatsApp: Bool
    let phoneNumber: String
    let email: String
    let creationDate: Date?
}

The screenshot


回答1:


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)




回答2:


You can do it as shown below:-

First create model class:-

import FirebaseFirestore
import Firebase

//#Mark:- Users model
struct CommentResponseModel {

    var createdAt : Date?
    var commentDescription : String?
    var documentId : String?

    var dictionary : [String:Any] {
        return [
                "createdAt": createdAt  ?? "",
                "commentDescription": commentDescription  ?? ""
        ]
    }

   init(snapshot: QueryDocumentSnapshot) {
        documentId = snapshot.documentID
        var snapshotValue = snapshot.data()
        createdAt = snapshotValue["createdAt"] as? Date
        commentDescription = snapshotValue["commentDescription"] as? String
    }
}

Then you can convert firestore document into custom object as shown below:-

func getJStoreUserFromDB() {
    db = Firestore.firestore()
    let user = Auth.auth().currentUser
    db.collection("users").document((user?.email)!).getDocument() { (document, error) in
        //        Convert firestore document your custom object
        let commentItem = CommentResponseModel(snapshot: document)
    }
}


来源:https://stackoverflow.com/questions/59548819/firebase-cloud-firestore-how-to-convert-document-to-a-custom-object-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!