iOS 12.1 / Swift 4.2
Every time the user taps on the Camera button in your app, you call this code. It firstly asks for permissions, and if the settings are still there from the past installs, UIAlertController pops up, allowing the user to open the Settings app on the device, and change camera permission settings.
OnCameraOpenButtonTap()
if UIImagePickerController.isSourceTypeAvailable(.camera) {
checkCameraAccess(isAllowed: {
if $0 {
DispatchQueue.main.async {
self.presentCamera()
}
} else {
DispatchQueue.main.async {
self.presentCameraSettings()
}
}
})
}
func checkCameraAccess(isAllowed: @escaping (Bool) -> Void) {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .denied:
isAllowed(false)
case .restricted:
isAllowed(false)
case .authorized:
isAllowed(true)
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { isAllowed($0) }
}
}
private func presentCamera() {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
private func presentCameraSettings() {
let alert = UIAlertController.init(title: "allowCameraTitle", message: "allowCameraMessage", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: { (_) in
}))
alert.addAction(UIAlertAction.init(title: "Settings", style: .default, handler: { (_) in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
}))
present(alert, animated: true)
}