loading...

iOS: How to generate image previews/thumbnails of various files

nemecek_f profile image Filip Němeček ・2 min read

Quick Look framework powers file previews across iOS and you can use its power to generate thumbnail images for all kinds of files. For example PDFs, text files, Pages documents, Word documents, Keynote presentations, 3D models for ARKit or images.

Let's look how to use it. The first step is to import QuickLookThumbnailing or QuickLook which includes the thumbnail part and offers more functionality.

The thumbnail generation is responsibility of the QLThumbnailGenerator .
Next step is to create its instance:

let previewGenerator = QLThumbnailGenerator()
let thumbnailSize = CGSize(width: 60, height: 90)
let scale = UIScreen.main.scale

I have also created constant that we will use later on.

This class offers method generateBestRepresentation which will create the thumbnail and report the result with completion handler. It automatically works on background thread so you don't have to worry about it. Just be careful trying to update UI from the handler.

The method takes single parameter and that is special "request" type QLThumbnailGenerator.Request.

Here is an example of one:

let request = QLThumbnailGenerator.Request(fileAt: url, size: self.thumbnailSize, scale: self.scale, representationTypes: .thumbnail)

The most important part is URL of the file for which to create thumbnail. If you have file in memory, you need to save it first and then use its URL to create thumbnail.

We have already specified the size and scale of the thumbnail. The last parameter specifies what kind of thumbnail we are interested in. For example you can ask for .icon or for .lowQualityThumbnail to get the result faster.

self.previewGenerator.generateBestRepresentation(for: request) { (thumbnail, error) in

    if let error = error {
        print(error.localizedDescription)
    } else if let thumb = thumbnail {
        thumb.uiImage // image available
    }

    group.leave()
}

The completion handler will give you instance of QLThumbnailRepresentation if the thumbnail generation was successful. On iOS you can use its property .uiImage to get instance of UIImage.

And that is how you can create thumbnails for your files 🙂

I have more complete example of Quick Look framework on GitHub that covers thumbnails as well as QLPreviewController to open these files in your app.

Thanks for reading!

Posted on Apr 6 by:

nemecek_f profile

Filip Němeček

@nemecek_f

Primarily iOS developer, I also like Django and Python. And dabble with JavaScript occasionally. Love reading and coffee.

Discussion

markdown guide