Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
    }
}
like image 377
onejuan Avatar asked Oct 21 '25 17:10

onejuan


1 Answers

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

like image 159
onejuan Avatar answered Oct 23 '25 07:10

onejuan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!