在iPhone应用程序中检测摄像头的存在?
我正在写一个iOS应用程序,我需要能够检测到设备是否有摄像头。 以前,我会检查设备是不是iPhone,因为只有iPhone有一个摄像头 – 但随着iPod Touch 4的推出,这不再是一个可行的select。 该应用程序没有相机的function,但相机的存在增加了function。
那么,任何人都可以给我提供代码,返回是否有摄像头?
您可以在UIImagePickerController中使用+isSourceTypeAvailable:
方法:
if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) // Has camera
是的,有一个API可以做到这一点:
BOOL isCamera = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
如果您正在使用AV Foundation类而不是UIImagePickerController,则可以执行以下操作:
BOOL hasCamera = ([[AVCaptureDevice devices] count] > 0);
如果您使用的是UIImagePickerController,则可能不值得,因为您必须将AVFoundation.framework添加到您的项目中。
迅速:
if UIImagePickerController.isSourceTypeAvailable(.Camera){ //Your code goes here //For example you can print available media types: print(UIImagePickerController.availableMediaTypesForSourceType(.Camera)) }
SWIFT 3
正如Juan Boero所写的那样:
if UIImagePickerController.isSourceTypeAvailable(.camera){ }
但我会添加另一个检查,看看用户是否允许访问相机,如苹果build议在他们的PhotoPicker示例( PhotoPicker示例Objective-C ):
*请注意你必须导入AVFoundation
let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if authStatus == AVAuthorizationStatus.denied { // Denied access to camera // Explain that we need camera access and how to change it. let dialog = UIAlertController(title: "Unable to access the Camera", message: "To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app.", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) dialog.addAction(okAction) self.present(dialog, animated:true, completion:nil) } else if authStatus == AVAuthorizationStatus.notDetermined { // The user has not yet been presented with the option to grant access to the camera hardware. // Ask for it. AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (grantd) in // If access was denied, we do not set the setup error message since access was just denied. if grantd { // Allowed access to camera, go ahead and present the UIImagePickerController. self.showImagePickerForSourceType(sourceType: UIImagePickerControllerSourceType.camera) } }) } else { // Allowed access to camera, go ahead and present the UIImagePickerController. self.showImagePickerForSourceType(sourceType: UIImagePickerControllerSourceType.camera) } func showImagePickerForSourceType(sourceType: UIImagePickerControllerSourceType) { let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = sourceType self.present(myPickerController, animated: true, completion: nil) }
如果您需要知道设备是否具有前置或后置摄像头,请使用以下命令:
isCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
检查相机是可用的(Swift)
if(!UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))