Hey everyone, I’m new to Swift and I’m having trouble getting data from Airtable using an API. My table is pretty basic, just title and image columns. Here’s what I’ve done so far:
I set up a ResponseDto struct to match the JSON structure:
struct ResponseDto: Decodable {
let records: [RecordDto]
struct RecordDto: Decodable {
let id: String
let createdTime: String
let fields: FieldsDto
}
struct FieldsDto: Decodable {
let title: String
let image: String
}
}
Then I have a Film struct:
struct Film: Identifiable {
let id = UUID()
let title: String
let image: String
}
I’m using a UsersViewModel class to fetch the data. It sets up a URL request with an authorization token and tries to decode the JSON response.
Looking at your error message, it seems the issue is with the third record in the response. This suggests that the problem might be inconsistent data in your Airtable.
Have you considered implementing some error handling or optional types in your decoding process? You could modify your FieldsDto struct to use optional properties:
struct FieldsDto: Decodable {
let title: String?
let image: String?
}
This approach would allow your decoder to handle cases where a field is missing without crashing. Additionally, you might want to add some logging to your decoding process to identify which specific records are causing issues. This can help you pinpoint and rectify data inconsistencies in your Airtable.
Remember, when working with external data sources, it’s always good practice to build in some resilience to handle unexpected or incomplete data.
hey there! sounds like ur havin a tough time i had similar issues w/ airtable. have u double-checked that ALL ur records in the table have both title and image fields filled? if even 1 is empty, it can mess up the decoding. also, make sure the field names in ur struct match EXACTLY what’s in airtable (case-sensitive). hope this helps!
I’ve been down this road before, and it can be frustrating. One thing that’s not immediately obvious is that Airtable’s API response structure can be a bit tricky. Have you considered making your FieldsDto struct use optional properties? Like this:
struct FieldsDto: Decodable {
let title: String?
let image: String?
}
This way, if a record is missing either the title or image, it won’t cause a decoding error. It’s a good practice when working with external APIs where you can’t always guarantee the data structure.
Also, make sure you’re using the correct API endpoint and that your authorization token has the necessary permissions. Sometimes, it’s the little things that trip us up. Keep at it, and you’ll get there!