我正在使用此代码使用照片框架从相册中检索照片, 我已成功检索到PHAssets并将其放入数组,但我无法将其转换为图像,在此过程中崩溃。
这是我的代码,
-(void)retrieveAllPhotoSetWithCompletionCallback:(void(^ __nonnull)(NSMutableArray * __nullable asset ,NSMutableArray * __nullable imageArray , BOOL complete))completionCallback{
self.requestOptions = [[PHImageRequestOptions alloc] init];
self.requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
self.requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
self.requestOptions.synchronous = YES;
NSMutableArray *assetsArray = [NSMutableArray new];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
[fetchResult enumerateObjectsUsingBlock:^(PHAsset *_Nonnull asset, NSUInteger idx, BOOL * _Nonnull stop) {
[assetsArray addObject:asset];
}];
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[assetsArray count]];
// assets contains PHAsset objects.
// __block UIImage *ima;
int i = 0;
for(PHAsset *asset in assetsArray) {
// This autorelease pool seems good (a1)
@autoreleasepool {
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:self.requestOptions
resultHandler:^(UIImage *image, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
//you can add autorelease pool here as well (a2)
@autoreleasepool {
//assetCount++;
NSLog(@"started requesting image %i", i);
NSError *error = [info objectForKey:PHImageErrorKey];
if (error)
NSLog(@"Image request error: %@",error);
else {
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%i.png",i]];
NSData *imageData = UIImagePNGRepresentation(image);
if(imageData) {
[imageData writeToFile:imagePath atomically:YES];
[images addObject:imagePath];
}
else {
NSLog(@"Couldn't write image data to file.");
}
NSLog(@"finished requesting image %i", i);
}
} //a2 ends here
});
}];
i++;
} // a1 ends here
}
completionCallback(assetsArray,images,YES);
}
答案 0 :(得分:0)
我认为问题在于requestImageForAsset:asset targetSize:PHImageManagerMaximumSize
这里你正在采用程序中可用的最大尺寸。这导致将最大尺寸的图像存储在RAM中。通过存储多个它会占用更多的RAM内存,它会崩溃。我调整了targetSize的大小,内存使用量比以前少了。