我正在尝试加载并显示UIImageView
中照片库(相机胶卷)中的最后一张照片,一切正常!除了一件事!如果库中没有可用的图像,则应用程序崩溃!这是我的代码:
-(void)importLastImage {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just photos.
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
// Chooses the photo at the last index
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:([group numberOfAssets]-1)]
options:0
usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
latestPhoto = [UIImage imageWithCGImage:[representation fullResolutionImage]];
_lastImage.image = latestPhoto;
}else {
//no image found !
}
}];
}
failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
NSLog(@"No groups");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ERROR" message:@"No Image found" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
[alert show];
}];
}
答案 0 :(得分:1)
我决定在这里发布一个您可以复制粘贴的代码段,其中包含上述评论中的建议。
如果我的英语不够清楚(我不是母语为英语的人),请提前抱歉。
您的崩溃是由于该行代码而造成的
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:([group numberOfAssets]-1)]
问题是,正如您所说,当库中没有可用的图像时,numberOfAssets
返回0,
由于您使用numberOfAssets - 1
创建索引,因此您基本上是在尝试创建一个负面索引,这会导致程序崩溃。
我只是添加了if
语句,以检查'if'numberOfAssets
(意味着它不是0),
只有这样,执行下面的枚举,因此,防止任何负面索引的情况。
无论如何,你在这里交配:
-(void)importLastImage {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just photos.
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
if([group numberOfAssets]) {
// Chooses the photo at the last index
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:([group numberOfAssets]-1)]
options:0
usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
latestPhoto = [UIImage imageWithCGImage:[representation fullResolutionImage]];
_lastImage.image = latestPhoto;
}else {
//no image found !
}
}];
} else {
NSLog(@"No images in photo library");
}
}
failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
NSLog(@"No groups");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ERROR" message:@"No Image found" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
[alert show];
}];
}