CodableFirebase icon indicating copy to clipboard operation
CodableFirebase copied to clipboard

How Can I Parse This Firestore Json Result ?

Open halilyuce opened this issue 4 years ago • 1 comments

Hello, firstly I wanna say thanks for this repo :)

I am working with firestore nowadays and I am going to freak out because of models. Finally, I found this repo but it is not working too. I do not know where is the problem :/

Error:

2020-03-30 23:33:18.794268+0300 Evde Kal[7506:202410] Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "date", intValue: nil)], debugDescription: "Not a dictionary", underlyingError: nil)): file /Users/halilyc/Desktop/Projects/Korona #EvdeKal/Korona #EvdeKal/Services/FirebasePosts.swift, line 38

This is my Post and Comments Model :

import Foundation import Firebase

struct Post: Decodable {
    let id: String
    let title: String
    let content: String
    let user: String
    let comments: [Comment]
    let date: Timestamp
}

struct Comment: Decodable {
    let content: String
    let user: String
    let date: Timestamp
}

and this is how I try to get it :

@Published var data = [Post]()

dbCollectionPosts.addSnapshotListener { (documentSnapshot, err) in
            if err != nil {
                print((err?.localizedDescription)!)
                return
            }else {
                print("read success")
            }
            
            documentSnapshot!.documentChanges.forEach { diff in
                // Real time create from server
                if (diff.type == .added) {
                    
                    let model = try! FirestoreDecoder().decode(Post.self, from: diff.document.data())
                    self.data.append(model)
                }
}

My firestore posts database :

image

Json Result :

["comments": <__NSArrayM 0x600003ae5c20>()
, "date": <FIRTimestamp: seconds=1585577477 nanoseconds=914969000>, 
"user": [email protected], 
"title": Salgından Sonra Yapılacaklar, 
"id": F9E42F21-11C3-4830-B07A-8F59B6A668CA, 
"content": Evet umarım bu salgını kısa sürede atlattıktan sonra en çok ne yapmak istiyorsunuz, neyi özlediniz ? :)]

halilyuce avatar Mar 30 '20 20:03 halilyuce

Did you conform Timestamp to TimestampType in your code?

like this: extension Timestamp: TimestampType {}

Patrick3131 avatar Apr 05 '20 00:04 Patrick3131