I have an NSCollectionView which is showing thumbnails of images and I have just switched to using QLThumbnailGenerator to fetch them. There are over 6,000 possible images that can be viewed and, if I scroll too fast, I start to get the wrong thumbnails returned from the generator. Is this a bug, or is there something I can do to fix this? Here is the code that is written inside the NSCollectionViewItem derived class…
var request: QLThumbnailGenerator.Request?
func loadImage()
{
if imageView?.image != NSImage(imageLiteralResourceName: "Placeholder")
{
return
}
request = QLThumbnailGenerator.Request(fileAt: url!, size: imageSize, scale: 1.0, representationTypes: [.lowQualityThumbnail])
QLThumbnailGenerator.shared.generateBestRepresentation(for: request!)
{
(thumbnail: QLThumbnailRepresentation?, error: Error?) -> Void in
if let request = self.request
{
QLThumbnailGenerator.shared.cancel(request)
}
DispatchQueue.main.async
{
[unowned self] in
if self.imageView?.image != NSImage(imageLiteralResourceName: "Placeholder")
{
return
}
let transition = CATransition()
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.duration = 0.3
imageView?.layer?.add(transition, forKey: nil)
imageView?.image = thumbnail?.nsImage
…
Well, I found the problem(s)
First, let me say in response to Willeke I was cancelling the request in the prepareForReuse method.
It turns out I was using the wrong QLThumbnailGenerator.
The problem was so subtle. One thing I didn't quote in my original post was that I had a var that holds a private QLThumbnailGenerator instance and it was this that I was using to cancel the request, even though I was using the shared instance in the loadImage method.
As soon as I switched the loadImage method to use the private var, everything started to work better.
I say better because there was still the occasion when the generator would return a nil image for some obscure reason.
So, for those times, I have a helper method that loads those thumbnails the "old fashioned" way…
… and the full code now reads…
I hope this is of use to anyone else who stumbles across this issue