Skip to content

Instantly share code, notes, and snippets.

@ksm
Created June 17, 2016 17:36
Show Gist options
  • Save ksm/2fb53ee4fa5aa61052f27815e6b5f829 to your computer and use it in GitHub Desktop.
Save ksm/2fb53ee4fa5aa61052f27815e6b5f829 to your computer and use it in GitHub Desktop.
One of many Photos.framework idiosyncrasies
/*
If you run loadThumbnail() in an *iPhone-only app that is installed on the iPad*,
the Photos framework will callback first with a degraded version of the requested asset image,
and then it will callback a second time with a nil image.
If you're not careful and you pass the nil image to your UIImageView, then you will never see the thumbnail.
The UIImageView will first get set with a proper UIImage, then soon after with a nil UIImage.
The solution is to ignore or discard any image that is nil.
So what happens if you try to setup PHImageRequestOptions to make sure that Photos framework only calls back once?
You do get only one callback then, except it's always with a nil image.
*/
func loadThumbnail(asset: PHAsset, targetSize: CGSize, completion: (Result<UIImage, NSError> -> Void)) {
let emptyOptions = PHImageRequestOptions()
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: emptyOptions) { image, dictionary in
if let image = image {
completion(Result(value: image))
} else {
let error = NSError(domain: "com.example.domain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Example localized description."])
completion(Result(error: error))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment