简体   繁体   中英

Firestore encodable not including Firestore DocumentID

Im using Firebase Firestore in my project, and I have figured out that I need to use @DocumentId to properly decode firebase "_id" property into my codable struct.

My issue is that I need to save the encoded object (for now I'm using userdefaults) and re-decode the object later on in my apps lifecycle.

When I encode my Firestore object with Firestore.encode, it loses the id property as it becomes encoded to [String: Any] so when I try to decode the fetched pre-encoded object, I'm unable to do so.

For now I am storing the ID property separately, and re-adding it to the object once decoded.

Is this the correct way to handle Firestore codable? Or is there a cleaner way to encode and then decode Firestore encoded objects?

As discussed here

The solution is to explicitly ask for the DocumentID wrapping of DocumentReference and then manually unwrap yourself. It looks like this:

 ref = try container.decode(DocumentID<DocumentReference>.self, forKey: .ref).wrappedValue

Also check these similar cases for more information:

How can I get the document ID when using Codable in Firestore?

Getting DocumentID when decoding Firestore struct with custom decodable

Getting document ID when decoding firestore document using Swift Codable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM