skip to Main Content

I have the following struct:

struct Recipe: Codable {
    @DocumentID var id: String?
    var vegetarian: Bool?
}

And this is how I’m parsing the data from Firestore:

do {
                    let decoder = JSONDecoder()
                    let recipeToDisplay = try decoder.decode(Recipe.self, from: data!)
                    
                    let uuid = UUID().uuidString
                    
                    FirestoreService.createRecipe(
                        documentId:uuid,
                        vegetarian: recipeToDisplay.vegetarian ?? false
                    ) { recipeURL in
                        print("success")
                    }
                }
                catch {
                    print("Error parsing response data: (error)")
                }

The catch statement is getting called and I’m getting the following error message: decodingIsNotSupported("DocumentID values can only be decoded with Firestore.Decoder").

All the documentation I’ve researched has pointed me towards using JSONDecoder() to parse the data and I can’t find anything on Firestore.Decoder. Is there a different way that I should be parsing the data?

2

Answers


  1. Chosen as BEST ANSWER

    The issue was that I was trying to decode id from a source that didn't have an id property. Excluding id from my CodingKeys resolved the issue.

    struct Recipe: Codable {
        @DocumentID var id: String?
        var vegetarian: Bool?
        
        private enum CodingKeys: String, CodingKey {
            case id
            case vegetarian
        }
    }
    

  2. My problem was that I wasn’t using an explicit Codable implementation. Unfortunately you have to add in all that nonsense boiler plate in order for it to work. Rather than use the default.

    So go ahead and bloat your model with:

    enum CodingKeys: String, CodingKey

    init(from decoder: Decoder)

    func encode(to encoder: Encoder)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search