Sau đây là một câu trả lời đã được làm sạch được cập nhật cho Swift 4.x:
Bắt đầu với iOS 10, bạn cũng phải yêu cầu quyền trong tệp info.plist để tránh sự cố:

Quyền riêng tư - Mô tả Sử dụng Máy ảnh
Bạn phải cung cấp một chuỗi được hiển thị cho người dùng với khóa này. Nếu không làm như vậy sẽ dẫn đến sự cố khi cố truy cập vào máy ảnh.
import AVFoundation
func checkCameraAccess() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .denied:
print("Denied, request permission from settings")
presentCameraSettings()
case .restricted:
print("Restricted, device owner must approve")
case .authorized:
print("Authorized, proceed")
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { success in
if success {
print("Permission granted, proceed")
} else {
print("Permission denied")
}
}
}
}
func presentCameraSettings() {
let alertController = UIAlertController(title: "Error",
message: "Camera access is denied",
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .default))
alertController.addAction(UIAlertAction(title: "Settings", style: .cancel) { _ in
if let url = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(url, options: [:], completionHandler: { _ in
})
}
})
present(alertController, animated: true)
}
Điều này sẽ kiểm tra bốn câu trả lời có thể có, sau đó yêu cầu quyền nếu có notDetermined
hoặc hướng người dùng đến cài đặt để bật nếu có denied
. Nếu đúng như vậy restricted
, người dùng hiện tại có thể không kích hoạt được, nhưng bạn nên cung cấp một số hình thức hướng dẫn cho họ.