Search code examples
iosswiftxcodefoundationquicklook

QLThumbnailGenerator saveBestRepresentation wrong content type Swift iOS 13+


When completing a task I have stumbled upon an iOS 13+ API that can solve my problem - https://developer.apple.com/documentation/quicklookthumbnailing/creating_quick_look_thumbnails_to_preview_files_in_your_app

It works as intended, but to complete my task I need to save created thumbnail to a disk, which I am trying to do using - https://developer.apple.com/documentation/quicklookthumbnailing/qlthumbnailgenerator/3237298-savebestrepresentation

func saveBestRepresentation(for request: QLThumbnailGenerator.Request, 
                         to fileURL: URL, 
                contentType: String, 
                 completion completionHandler: @escaping (Error?) -> Void)

Here is my code:

/// Uses quick look to asynchronously create best possible thumbnail image at path
static func createThumbnailFor(_ inputUrl: URL, at outputUrl: URL) {
    let size: CGSize = CGSize(width: 60, height: 90)
    let scale = UIScreen.main.scale

// Create the thumbnail request.
let request =
    QLThumbnailGenerator.Request(
        fileAt: inputUrl,
        size: size,
        scale: scale,
        representationTypes: .all)

// Retrieve the singleton instance of the thumbnail generator and generate the thumbnails.
let generator = QLThumbnailGenerator.shared
generator.saveBestRepresentation(for: request, to: outputUrl, contentType: "image/jpg") { (error) in
    if let error = error {
        print(error.localizedDescription)
    }
}

}

I am receiving the following error:

2020-07-28 13:08:01.259835+0300 SomeAppName[4748:1236635] *** Terminating app due to uncaught exception 'QLThumbnailGeneratorInvalidContentType', reason: 'image/jpg is not a supported image type'

I have tried many different types and looked through the headers but it only says that 'The content type of the thumbnail image that you want to save. Use a type that is supported by CGImageDestination, such as kUTTypePNG or kUTTypeJPEG.'. Unfortunately kUTTypePNG and kUTTypeJPEG are both deprecated. What content type should work in this case?


Solution

  • The iOS 14 way:

    At the top of the file, import UniformTypeIdentifiers. Now change

    contentType: "image/jpg"
    

    to

    contentType: UTType.jpeg.identifier