usuario plus para modelo gratis español emc apple a1387 a1332 3gs ios swift

ios - plus - ¿Cómo verificar si el usuario dio permiso para usar la cámara?



manual iphone modelo a1387 emc 2430 (6)

Intentando escribir esto:

if usergavepermissiontousercamera opencamera else showmycustompermissionview

No se pudo encontrar una forma actual de hacer esta tarea simple.
Nota: También debería funcionar iOS7 incluso si requiere un método diferente


Esto abrirá la cámara cuando el usuario otorgue permiso. De lo contrario, muestre alerta por pedir permiso.

func openCamera(){ let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) switch (authStatus){ case .notDetermined: showAlert(title: "Unable to access the Camera", message: "To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app.") case .restricted: showAlert(title: "Unable to access the Camera", message: "To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app.") case .denied: showAlert(title: "Unable to access the Camera", message: "To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app.") case .authorized: alert.dismiss(animated: true, completion: nil) if(UIImagePickerController .isSourceTypeAvailable(.camera)){ picker.sourceType = .camera picker.showsCameraControls=true picker.allowsEditing=true self.viewController!.present(picker, animated: true, completion: nil) } } }

después de esta llamada esta función para mostrar alerta

func showAlert(title:String, message:String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(okAction) let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: { _ in // Take the user to Settings app to possibly change permission. guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { if #available(iOS 10.0, *) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in // Finished opening URL }) } else { // Fallback on earlier versions UIApplication.shared.openURL(settingsUrl) } } }) alert.addAction(settingsAction) self.viewController!.present(alert, animated: true, completion: nil) }


La siguiente es una respuesta limpia actualizada para Swift 4.x:

A partir de iOS 10, también debe solicitar permiso en el archivo info.plist para evitar un bloqueo:

Privacidad - Descripción del uso de la cámara

Debe proporcionar una cadena que se presente al usuario con esta clave. De lo contrario, se producirá un bloqueo al intentar acceder a la cámara.

import AVFoundation func checkCameraAccess() { switch AVCaptureDevice.authorizationStatus(for: .video) { case .denied: print("Denied, request permission from settings") presentCameraSettings() case .restricted: print("Restricted, device owner must approve") case .authorized: print("Authorized, proceed") case .notDetermined: AVCaptureDevice.requestAccess(for: .video) { success in if success { print("Permission granted, proceed") } else { print("Permission denied") } } } } func presentCameraSettings() { let alertController = UIAlertController(title: "Error", message: "Camera access is denied", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Cancel", style: .default)) alertController.addAction(UIAlertAction(title: "Settings", style: .cancel) { _ in if let url = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(url, options: [:], completionHandler: { _ in // Handle }) } }) present(alertController, animated: true) }

Esto probará las cuatro respuestas posibles y, a continuación, solicitará permiso si no está notDetermined o dirigirá al usuario a la configuración para habilitarlo si se denied . Si está restricted , es posible que el usuario actual no pueda habilitarlo, pero debe proporcionarles algún tipo de orientación.


Modifiqué la respuesta anterior y eliminé la solicitud inicial, ya que cuando queremos usar la cámara del dispositivo, el sistema solicita permisos en sí:

func checkPermissions() { let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) switch authStatus { case .authorized: setupCamera() case .denied: alertPromptToAllowCameraAccessViaSetting() default: // Not determined fill fall here - after first use, when is''t neither authorized, nor denied // we try to use camera, because system will ask itself for camera permissions setupCamera() } } func alertPromptToAllowCameraAccessViaSetting() { let alert = UIAlertController(title: "Error", message: "Camera access required to...", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Cancel", style: .default)) alert.addAction(UIAlertAction(title: "Settings", style: .cancel) { (alert) -> Void in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) }) present(alert, animated: true) }


Puede importar el marco de AVFoundation y utilizar el métodoautorizationStatus authorizationStatus(for:) que se muestra a continuación y manejar los casos respectivos.

switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: // The user has previously granted access to the camera. self.setupCaptureSession() case .notDetermined: // The user has not yet been asked for camera access. AVCaptureDevice.requestAccess(for: .video) { granted in if granted { self.setupCaptureSession() } } case .denied: // The user has previously denied access. return case .restricted: // The user can''t grant access due to restrictions. return }


Puede usar el siguiente código para hacer lo mismo:

if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == AVAuthorizationStatus.Authorized { // Already Authorized } else { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in if granted == true { // User granted } else { // User rejected } }) }

NOTA:

  1. Asegúrese de agregar el Marco AVFoundation en la sección Enlace binario de las fases de compilación
  2. Debe escribir import AVFoundation en su clase para importar AVFoundation

SWIFT 3

if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == AVAuthorizationStatus.authorized { // Already Authorized } else { AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in if granted == true { // User granted } else { // User Rejected } }) }

Swift 4

if AVCaptureDevice.authorizationStatus(for: .video) == .authorized { //already authorized } else { AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in if granted { //access allowed } else { //access denied } }) }


Solución actualizada Swift 3.0

func callCamera(){ let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerControllerSourceType.camera self.present(myPickerController, animated: true, completion: nil) NSLog("Camera"); } func checkCamera() { let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) switch authStatus { case .authorized: callCamera() // Do your stuff here i.e. callCameraMethod() case .denied: alertPromptToAllowCameraAccessViaSetting() case .notDetermined: alertToEncourageCameraAccessInitially() default: alertToEncourageCameraAccessInitially() } } func alertToEncourageCameraAccessInitially() { let alert = UIAlertController( title: "IMPORTANT", message: "Camera access required for capturing photos!", preferredStyle: UIAlertControllerStyle.alert ) alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) alert.addAction(UIAlertAction(title: "Allow Camera", style: .cancel, handler: { (alert) -> Void in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) })) present(alert, animated: true, completion: nil) } func alertPromptToAllowCameraAccessViaSetting() { let alert = UIAlertController( title: "IMPORTANT", message: "Camera access required for capturing photos!", preferredStyle: UIAlertControllerStyle.alert ) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel) { alert in if AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo).count > 0 { AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in DispatchQueue.main.async() { self.checkCamera() } } } } ) present(alert, animated: true, completion: nil) }