onejuan
onejuan

Reputation: 470

Getting document ID when decoding firestore document using Swift Codable

I'm using a class to decode retrieved firestore documents, and it works as expected if I don't want to manipulate the data:

class Room: Identifiable, Codable {

    @DocumentID public var id:String?
    var name:String

}

However if I try to use my own init to set values, I can't get the firestore document ID?

class Room: Identifiable, Codable {

    @DocumentID public var id:String?
    var name:String
    
    
    enum Keys:String, CodingKey {
        case name
        case capacity
        case photo = "url"
    }
    
    required init(from decoder: Decoder) throws {

        // How do I get the document ID to set the id value?

        let container = try decoder.container(keyedBy: Keys.self)
        name = try container.decode(String.self, forKey: .name)
        capacity = try container.decode(Int.self, forKey: .capacity)
        photo = try container.decode(String.self, forKey: .photo)

        // Do some more stuff here...
    }
}

Upvotes: 4

Views: 1080

Answers (1)

onejuan
onejuan

Reputation: 470

Found the answer elsewhere, and this works perfectly. Posting for anyone else who arrives here with the same query.

TL;DR -

Use the following to decode the DocumentReference in your init function:

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

Longer explanation: I won't pretend to understand this 100%, but there's a good explanation here https://github.com/firebase/firebase-ios-sdk/issues/7242

Upvotes: 7

Related Questions