0

I am using this code to get the latest photo from the cameraRoll:

- (void) getTheLatestPhoto{
        ALAssetsLibrary *cameraRoll = [[ALAssetsLibrary alloc] init];
        [cameraRoll enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *images, BOOL *stop) {
            [images setAssetsFilter:[ALAssetsFilter allPhotos]];
            [images enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[images numberOfAssets] - 1] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
             {
                 if (result) {

                     ALAssetRepresentation *rep = [result defaultRepresentation];
                     self.sharingImage = [UIImage imageWithCGImage:[rep fullScreenImage]];
                 }
             }];
        }
                                failureBlock: ^(NSError *error) {
                                    NSLog(@"An error occured: %@",error);
                                }];
    }

As it is, if the library cameraRoll is empty, the app will crash with this error:

Terminating app due to uncaught exception 'NSRangeException', reason: 'indexSet count or lastIndex must not exceed -numberOfAssets'

I understand that my indexSet is higher than the numberOfAssets due to this:

[images enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[images numberOfAssets] - 1]

At this point my question is "where do I put a condition that allow me to check if the assets is zero?"

If cameraRoll has more than zero, I will let the code continue, but if the count is zero, I would like to handle the issue this way as oppose to let it crash:

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];

Thanks for your help!

4

1 回答 1

0

if([images numberOfAssets]>0)在行前添加 enumerateAssetsAtIndexes并继续代码...

或者 if([images numberOfAssets]<=0)然后

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
于 2013-05-10T13:07:13.530 回答