Resume Presentations Open-Source Android iOS

06 Jun 2016
Accessing Camera and Photos in iOS

Accessing camera

Requesting access for media types

One can request access to the camera/microphone using AVCaptureDevice::requestAccessForMediaType:completionHandler:. Note however that completionHandler will be called in a background thread. If you want to do some UIKit operation, you need to dispatch to the main queue. One good approach is the following:

    void (^cb)(BOOL) = ^void(BOOL granted) {
        if (!granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //show alert
            });
        }
    };
    
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == ALAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:cb];
    } else {
        cb(status == AVAuthorizationStatusAuthorized);
    }

Accessing photos

Requesting access

Same process as with AV, we must check the Photos framework.

void (^cb)(PHAuthorizationStatus) = ^void(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
   	   //handle denied access                     
        }
    };
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus newStatus) {
            cb(newStatus);
        }];
    } else {
        cb(status);
    }

In this case, requestAuthorization’s callback is called in the same thread. Note that, until the user has seen the permission prompt, calls to fetch images from the library will return empty objects, and attempting to write files into the library will fail.


PS: I know I am not supposed to tell you what to do, but, you know, you could always follow me on Twitter