Swift 5.2
For reference
https://gist.github.com/hadanischal/33054429b18287c12ed4f4b8d45a1701
Info.plist
<key>NSCameraUsageDescription</key>
<string>Access camera</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Access PhotoLibrary</string>
AVFoundationHelper
import AVFoundation
enum CameraStatus {
case notDetermined
case restricted
case denied
case authorized
}
protocol AVFoundationHelperProtocol: AnyObject {
// MARK: - Check and Respond to Camera Authorization Status
var authorizationStatus: CameraStatus { get }
// MARK: - Request Camera Permission
func requestAccess(completionHandler handler: @escaping (Bool) -> Void)
}
final class AVFoundationHelper: AVFoundationHelperProtocol {
// MARK: - Check and Respond to Camera Authorization Status
var authorizationStatus: CameraStatus {
let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
switch cameraAuthorizationStatus {
case .notDetermined:
return CameraStatus.notDetermined
case .authorized:
return CameraStatus.authorized
case .restricted:
return CameraStatus.restricted
case .denied:
return CameraStatus.denied
@unknown default:
return CameraStatus.notDetermined
}
}
// MARK: - Request Camera Permission
func requestAccess(completionHandler handler: @escaping (Bool) -> Void) {
AVCaptureDevice.requestAccess(for: .video, completionHandler: { accessGranted in
handler(accessGranted)
})
}
}
ViewController
import UIKit
final class ViewController: UIViewController {
@IBOutlet var cameraAccessButton: UIButton!
@IBOutlet var photoImageView: UIImageView!
private var model: AVFoundationHelperProtocol = AVFoundationHelper()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func cameraButtonPressed(_: Any) {
let status = model.authorizationStatus
switch status {
case .notDetermined:
model.requestAccess { hasAccess in
if hasAccess {
DispatchQueue.main.async {
self.showCameraReader()
}
} else {
self.alertCameraAccessNeeded()
}
}
case .restricted, .denied:
alertCameraAccessNeeded()
case .authorized:
showCameraReader()
}
}
private func alertCameraAccessNeeded() {
let appName = "This app Name"
let alert = UIAlertController(title: "This feature requires Camera Access",
message: "In iPhone settings, tap \(appName) and turn on Camera access",
preferredStyle: UIAlertController.Style.alert)
let actionSettings = UIAlertAction(title: "Settings", style: .default, handler: { _ -> Void in
guard let settingsAppURL = URL(string: UIApplication.openSettingsURLString) else { return }
UIApplication.shared.open(settingsAppURL)
})
let actionCancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { _ -> Void in
})
alert.addAction(actionSettings)
alert.addAction(actionCancel)
present(alert, animated: true, completion: nil)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private func showCameraReader() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera
imagePicker.allowsEditing = true
imagePicker.delegate = self
present(imagePicker, animated: true)
} else if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
imagePicker.delegate = self
present(imagePicker, animated: true)
} else {
// TODO: Implement proper alert
alertCameraAccessNeeded()
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
picker.dismiss(animated: true)
guard let image = info[.editedImage] as? UIImage else {
print("No image found")
return
}
photoImageView.image = image
// print out the image size as a test
print(image.size)
}
}
Objective C
In .h file
@interface ABCViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)takePhoto: (UIButton *)sender;
- (IBAction)selectPhoto:(UIButton *)sender;
@end
In .m file
@interface ABCViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
- (IBAction)takePhoto:(UIButton *)sender {
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Device has no camera"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[myAlertView show];
} else {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
}
- (IBAction)selectPhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
UIImagePickerController
'stakePicture
method is one way.