Home > front end >  I keep getting a keyNotFound coding keys error
I keep getting a keyNotFound coding keys error

Time:04-05

I am using the google books api and I keep getting this error:

keyNotFound(CodingKeys(stringValue: "industryIdentifiers", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "items", intValue: nil), _JSONKey(stringValue: "Index 2", intValue: 2), CodingKeys(stringValue: "volumeInfo", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: "industryIdentifiers", intValue: nil) ("industryIdentifiers").", underlyingError: nil))

These are my structs:

struct Book: Identifiable, Codable {
    let id = UUID()
    let volumeInfo: VolumeInfo
}

struct VolumeInfo: Codable {
    let title, publishedDate: String?
    let authors: [String]?
    let publisher, description: String?
    let imageLinks: ImageLinks?
    let industryIdentifiers: [IndustryIdentifier]
    let averageRating: Double?
    let id: String?
}
// MARK: - IndustryIdentifier
struct IndustryIdentifier: Codable {
    let identifier: String
}

struct ApiResponse: Codable {
    let kind: String
    let totalItems: Int
    let items: [Book]
}

struct ImageLinks: Codable {
    let smallThumbnail, thumbnail: String
}

and this is how I'm calling it:

override func viewDidLoad() {
 super.viewDidLoad()
          
 var searchText = "the deal"
 searchBooks()
        
  }

    func searchBooks() {
            if let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=\(searchText)") {
                URLSession.shared.dataTask(with: url) { data, response, error in
                    if let data = data {
                        do {
                            let response = try JSONDecoder().decode(ApiResponse.self, from: data)
                            self.bookInfo = response.items
            
                        } catch {
                            print(error)
                        }
                        
                    }
                    DispatchQueue.main.async {
                        self.tableview.reloadData()
                    }
                    
                }.resume()
            }
        }

CodePudding user response:

It seems industryIdentifiers is an optional value

let industryIdentifiers: [IndustryIdentifier]?

should fix the issue.

  • Related