【发布时间】:2014-11-14 01:46:38
【问题描述】:
当应用尝试访问 iOS 中的相机 API 时,会显示操作系统级别的警报视图。 此处的用户必须允许访问相机或禁用访问。
我的问题是如何获得有关用户选择的通知..?
假设他选择了不允许访问,是否有任何通知可以在我的应用中使用..?
感谢任何帮助。
【问题讨论】:
标签: ios iphone avcapturesession
当应用尝试访问 iOS 中的相机 API 时,会显示操作系统级别的警报视图。 此处的用户必须允许访问相机或禁用访问。
我的问题是如何获得有关用户选择的通知..?
假设他选择了不允许访问,是否有任何通知可以在我的应用中使用..?
感谢任何帮助。
【问题讨论】:
标签: ios iphone avcapturesession
您可以检查当前授权状态,并手动请求授权,而不是让操作系统在摄像头出现时显示警报视图。这样,当用户接受/拒绝您的请求时,您会收到回调。
迅速:
let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
if status == AVAuthorizationStatus.Authorized {
// Show camera
} else if status == AVAuthorizationStatus.NotDetermined {
// Request permission
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) -> Void in
if granted {
// Show camera
}
})
} else {
// User rejected permission. Ask user to switch it on in the Settings app manually
}
如果用户之前拒绝了请求,调用requestAccessForMediaType 将不会显示警报并会立即执行完成块。在这种情况下,您可以选择显示自定义警报并将用户链接到设置页面。有关此here 的更多信息。
【讨论】:
取自 Kens 的回答,我创建了这个 Swift 3 协议来处理权限访问:
import AVFoundation
protocol PermissionHandler {
func handleCameraPermissions(completion: @escaping ((_ error: Error?) -> Void))
}
extension PermissionHandler {
func handleCameraPermissions(completion: @escaping ((_ error: Error?) -> Void)) {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
switch status {
case .authorized:
completion(nil)
case .restricted:
completion(ClientError.noAccess)
case .notDetermined:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
if granted {
completion(nil)
} else {
completion(ClientError.noAccess)
}
}
case .denied:
completion(ClientError.noAccess)
}
}
}
然后您可以遵循此协议并在您的类中调用它,如下所示:
handleCameraPermissions() { error in
if let error = error {
//Denied, handle error here
return
}
//Allowed! As you were
【讨论】: