在ios模拟器上运行时,当imagePicker的来源是Camera时,应用程序崩溃?

fAi*_*SaL 5 objective-c ios

当我将 imagePicker 的源类型指定为 Camera 时,我的应用程序在模拟器上崩溃,但在设备上运行良好。我已经在“plist”中添加了相机和照片库的权限。

崩溃日志:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“源类型 1 不可用”

代码:

-(void)showImgPickerWithSourceType:(UIImagePickerControllerSourceType)sourceType
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;
picker.sourceType = sourceType;
picker.allowsEditing = YES;
[(UINavigationController *)[[self.window.subviews objectAtIndex:0] nextResponder] presentViewController:picker animated:YES completion:nil];
}
Run Code Online (Sandbox Code Playgroud)

由于我尝试在模拟器上访问相机,是否会发生崩溃?这里会出现什么问题。我错过了什么?

Ron*_*ara 2

您可以使用isSourceTypeAvailable方法来UIImagePickerController检查给定的源类型是否可用。

\n\n
+ (BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

如果设备支持指定的源类型,则返回 YES;如果指定的源类型不可用,则为 NO。

\n\n

由于媒体源可能不存在或不可用,\n 设备可能并不总是支持所有源类型。例如,如果您尝试从 user\xe2\x80\x99s 库中选取图像,而该库为空,则此方法将返回 NO。同样,如果相机已在使用中,则此方法返回 NO。

\n\n

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

\n
\n\n

您可以使用以下代码行添加对可用或不可用源类型的检查:

\n\n
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {\n\n    UIImagePickerController *picker = [[UIImagePickerController alloc] init];\n    picker.delegate = self;\n    picker.sourceType = sourceType;\n    picker.allowsEditing = YES;\n    [(UINavigationController *)[[self.window.subviews objectAtIndex:0] nextResponder] presentViewController:picker animated:YES completion:nil];     \n\n}\nelse{\n\n    //it is simulator or device with no camera source\n\n    // handle accordingly\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

参考:https://developer.apple.com/reference/uikit/uiimagepickercontroller/1619144-issourcetypeavailable ?language=objc

\n