iPod Touch(第 5 代)'Source type 1 not available' 在使用 UIImagePickerControllerSourceTypeCamera 时崩溃

iPod Touch (5th gen) 'Source type 1 not available' crash when using UIImagePickerControllerSourceTypeCamera

iPod Touch(第 5 代)同时具有前置和后置摄像头,所以当我尝试显示 sourceType 为 UIImagePickerControllerSourceTypeCamera 的 UIImagePickerController 时,为什么我的应用程序会崩溃

- (void)openImagePickerType:(NSString *)type
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    if([type isEqualToString:kImagePickerCameraString])
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    if([type isEqualToString:kImagePickerLibraryString])
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.allowsEditing = NO;

    if(IS_IPAD && imagePicker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){
        DLog(@"show popopver image picker");


        UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
        [popover presentPopoverFromRect:self.cameraButton.bounds inView:self.cameraButton permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        self.popover = popover;

    }else{
        [self presentViewController:imagePicker animated:YES completion:nil];
    }


}

首先,您应该始终验证资源是否可用,请尝试使用:

if(IS_IPAD && imagePicker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){

  if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
    // present the popover
  }

  else {
    // HEY, YOU CAN'T USE THIS
  }

}

来自official docs

Because a media source may not be present or may be unavailable, devices may not always support all source types. For example, if you attempt to pick an image from the user’s library and the library is empty, this method returns false. Similarly, if the camera is already in use, this method returns false.

Before attempting to use an UIImagePickerController object to pick an image, you must call this method to ensure that the desired source type is available.

其次,我没看清楚这部分应该在什么时候执行:

else {
  [self presentViewController:imagePicker animated:YES completion:nil];
}

您应该这样指定:

if(IS_IPAD && imagePicker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){

  if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
    // present the popover
  }
  else {
    // HEY, YOU CAN'T USE THIS
  }

else if (imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {

  if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    // present the popover
  }
  else {
    // HEY, YOU CAN'T USE THIS
  }

  ...

}
  1. 当您始终可以直接使用 UIImagePickerControllerSourceType 作为 var 的类型时,为什么要为 type var 使用 NSString 类型