I have an array filled with PHAsset
objects (https://developer.apple.com/library/prerelease/ios/documentation/Photos/Reference/PHAsset_Class/index.html), and I want
image may be nil(seldom). It's better to evaluate, otherwise array add nil will crash app.
if(image){
ima = image;
[images addObject:ima];
}
Swift 3.0 Answer
let photoAsset = asset
let manager = PHImageManager.default()
var options: PHImageRequestOptions?
options = PHImageRequestOptions()
options?.resizeMode = .exact
options?.isSynchronous = true
manager.requestImage(
for: photoAsset,
targetSize: PHImageManagerMaximumSize,
contentMode: .aspectFill,
options: options
) { [weak self] result, _ in
completion(result)
}
options?.isSynchronous = true is very important
BOOL synchronous; // return only a single result, blocking until available (or failure). Defaults to NO
Swift 4.2
extension PHAsset {
var image : UIImage {
var thumbnail = UIImage()
let imageManager = PHCachingImageManager()
imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { image, _ in
thumbnail = image!
})
return thumbnail
}
}
let image = asset.image
For anyone struggling as much as I had on this issue, this is the way to go.
First set the requestOptions as:
self.requestOptions = [[PHImageRequestOptions alloc] init];
self.requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
self.requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
// this one is key
self.requestOptions.synchronous = YES;
and if there are multiple assets in an array filled with PHAsset objects, then add this code:
self.assets = [NSMutableArray arrayWithArray:assets];
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[assets count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in self.assets) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:self.requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
and now the images
array contains all the images in uiimage
format.