swiftgoogle-booksgoogle-books-api

How to get higher res image from Google Books Api?


When I try to get a higher resolution image from the google books API it only gives me the small thumbnail size that is 128 X 209 and I can't get a larger image

This is my url:

if let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=colleen+hoover")

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 averageRating: Double?
    
}

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 downloading the image from the url

extension UIImageView {
    func downloaded(from url: URL, contentMode mode: ContentMode = .scaleAspectFit) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
            else { return }
            DispatchQueue.main.async() { [weak self] in
                self?.image = image
            }
        }.resume()
    }
    func downloaded(from link: String, contentMode mode: ContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }
}

Solution

  • Ok, I figured out a way to fix this but I'm not sure if it's the best solution.

    Instead of getting the image URL from the struct and using the thumbnail, I used this URL instead and just change the bookImgId variable to your book id

    https://books.google.com/books/publisher/content/images/frontcover/\(bookImgId)?fife=w400-h600&source=gbs_api
    

    This part of the URL is where you will change the image size to whatever you want

    ?fife=w400-h600