Within my swift app, this is the code I have to request for microphone and camera permissions.
class func requestCameraPermission(completionBlock:(Bool throws -> Void)) rethrows {
if (AVCaptureDevice.respondsToSelector(Selector("requestAccessForMediaType:completionHandler"))) {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: {
granted in
dispatch_async(dispatch_get_main_queue()) {
try! completionBlock(granted)
}
})
} else {
try! completionBlock(true)
}
}
class func requestMicrophonePermission(completionBlock:(Bool throws -> Void)) rethrows {
if AVAudioSession.sharedInstance().respondsToSelector("requestRecordPermission:") {
AVAudioSession.sharedInstance().requestRecordPermission {
granted in
dispatch_async(dispatch_get_main_queue()) {
try! completionBlock(granted)
}
}
}
}
And this is the code I have to attach the camera and show an error if some permissions are missing.
func attachCamera() {
do {
try self.camera.start()
} catch BESwiftCameraErrorCode.CameraPermission {
self.showCameraPermissionAlert()
} catch BESwiftCameraErrorCode.MicrophonePermission {
self.showMicrophonePermissionAlert()
print("mic error!!")
} catch {
self.showUnknownErrorAlert()
}
}
I have tried not allowing for the camera permission. I see an alert box saying that I need camera permissions. The app does not crash.
But when I try not allowing the microphone permission, the app crashes.
With this line highlighted in the crash log:
try! completionBlock(granted)
And this error:
fatal error: 'try!' expression unexpectedly raised an error: TestApp.CameraErrorCode.MicrophonePermission: file /Library/Caches/com.apple.xbs/Sources/swiftlang_PONDEROSA/swiftlang_PONDEROSA-700.1.101.6/src/swift/stdlib/public/core/ErrorType.swift, line 50
What is causing this? How do I get the microphone permission alert to show instead of the app crashing?