2014-12-27 2 views
0

Я пытаюсь загрузить и показать последнюю фотографию из фотобиблиотеки (Camera roll) в UIImageView, все работает отлично! кроме одного! если в библиотеке нет изображения, тогда приложение падает! Вот мой код:Detect Photo Library is empty

-(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

Попробуйте добавить некоторые условия вдоль линии 'если ([группа numberOfAssets])' перед вызовом 'enumerateAssetsAtIndexes: варианты: usingBlock:' и посмотреть, если он решает ваши вопрос. – AMI289

ответ

1

я решил разместить здесь фрагмент кода, который можно просто скопировать пасту, которая содержит предложение от моего комментария выше.
Извините, если мой английский не достаточно ясен (я не являюсь носителем английского языка).

Ваши аварии из-за этой строки кода
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:([group numberOfAssets]-1)]

Проблема заключается в том, как вы сказали, когда нет изображения доступны в библиотеке, numberOfAssets возвращает 0,
И так как вы создайте индекс с numberOfAssets - 1, вы в основном пытаетесь создать отрицательный индекс, который разбивает вашу программу.

Я просто добавил 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]; 

    }]; 

}