Jeremy Jeremy - 3 months ago 43
Swift Question

privacy issues with camera and photo library in swift

My app initially had no problems accessing both camera and photo library on various devices.

Now I find that on some devices I can't get access to the camera or photo library, and the app does not appear at all in the privacy settings after I have tried to access camera and photos.

No matter what I do I can't get IOS to recognize my app.

What can I do to to access the camera and photo library, and have my app appear in the privacy settings?
code:

@IBAction func openCameraButton(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) == true {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera//UIImagePickerControllerSourceType.Camera;
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}else{
noCamera()

}
}
@IBAction func openPhotoLibraryButton(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) == true {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
imagePicker.allowsEditing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}else{
noAccess()
}
}

Answer

I use this code for checking accessibly and requesting it if needed:

import AVFoundation
import Photos

func getCameraAccessibilityAndRequestIfNeeded(completion: (isAccesible: Bool)->Void) {
    let authorizationState = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
    switch authorizationState {
    case .NotDetermined:
        AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (didAllow) in
            completion(isAccesible: didAllow)
        })
    case .Restricted:
        completion(isAccesible: false)
    case .Denied:
        completion(isAccesible: true)
    case .Authorized:
        completion(isAccesible: true)
 }
}

func getPhotoRollAccessibilityAndRequestIfNeeded(completion: (isAccesible: Bool)->Void) {
    PHPhotoLibrary.requestAuthorization { (status) in
        switch status {
        case .Authorized:
            completion(isAccesible: true)
        case .Restricted, .Denied , .NotDetermined:
            completion(isAccesible: false)
        }
    }
}

Usage:

self.getCameraAccessibilityAndRequestIfNeeded { (isAccesible) in
            if isAccesible {
                // Access confirmed
            } else {
                // No access
            }
        }

        self.getPhotoRollAccessibilityAndRequestIfNeeded { (isAccesible) in
            if isAccesible {
                // Access confirm
            } else {
                // No access
            }
        }
Comments