iPod Touch(第5代)'源类型1不可用'使用UIImagePickerControllerSourceTypeCamera时崩溃

时间:2015-06-22 17:07:58

标签: ios objective-c ipod-touch

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

- (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];
    }


}

1 个答案:

答案 0 :(得分:0)

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

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

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

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

}

来自official docs

  

由于媒体来源可能不存在或可能不可用,   设备可能并不总是支持所有源类型。例如,如果你   尝试从用户的库中选择一个图像,该库是   为空,此方法返回false。同样,如果相机已经存在   在使用中,此方法返回false。

     

在尝试使用UIImagePickerController对象选择之前   图像,您必须调用此方法以确保所需的源   类型可用。

其次,我不清楚何时应该执行这部分:

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. 当您可以直接使用type var作为var的类型时,为什么要为UIImagePickerControllerSourceType使用NSString类型