Hey everyone! I’m pretty new to Swift development and running into some issues while working with Airtable’s API in my SwiftUI app.
I have a basic table with book information that includes name and cover fields. Here’s what the API returns:
{
"records":[
{
"id":"recX1Y2Z3A4B5C6D7",
"createdTime":"2022-11-15T14:22:18.000Z",
"fields":{
"name":"The Magic Kingdom",
"cover":"coverMagic"
}
},
{
"id":"recA8B9C0D1E2F3G4",
"createdTime":"2022-11-15T14:22:19.000Z",
"fields":{
"name":"Silent Waters",
"cover":"coverSilent"
}
}
]
}
I created this response structure:
struct AirtableResponse: Decodable {
let records: [BookRecord]
struct BookRecord: Decodable {
let id: String
let createdTime: String
let fields: BookFields
}
struct BookFields: Decodable {
let name: String
let cover: String
}
}
And my main data model:
struct Book: Identifiable {
let id = UUID()
let name: String
let cover: String
}
Here’s my network call:
class BooksViewModel: ObservableObject {
@Published var books = [Book]()
func loadBooks() async {
guard let endpoint = URL(string: "https://api.airtable.com/v0/appXYZ123/Books") else {
return
}
var apiRequest = URLRequest(url: endpoint)
apiRequest.httpMethod = "GET"
apiRequest.setValue(
"Bearer mytoken",
forHTTPHeaderField: "Authorization"
)
let networkTask = URLSession.shared.dataTask(with: apiRequest) { data, response, error in
if let error = error {
print(error)
} else if
let data = data,
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 {
do {
let apiResponse: AirtableResponse = try JSONDecoder().decode(AirtableResponse.self, from: data)
DispatchQueue.main.async {
self.books = []
}
for item in apiResponse.records {
DispatchQueue.main.async {
self.books.append(
Book(name: item.fields.name, cover: String(item.fields.cover))
)
}
}
} catch {
print(error)
}
}
}
networkTask.resume()
}
}
I keep getting this decoding error:
keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "records", intValue: nil), _JSONKey(stringValue: "Index 3", intValue: 3), CodingKeys(stringValue: "fields", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"name\", intValue: nil) (\"name\").", underlyingError: nil))
I’ve been stuck on this for hours and tried different approaches but can’t figure out what’s wrong. Any ideas what might be causing this?