前提
- iOS16以上
xxx.swift
import AVFoundation
struct XxxView: View {
@State var showAlert = false;
var body: some View {
checkCamera()
return ZStack(alignment: .bottom) {
...
}
.alert("カメラを使用できません", isPresented: $showAlert) {
Button("Cancel") {}
Button("設定") {
guard let settingsURL = URL(string: UIApplication.openSettingsURLString ) else {
return
}
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
}
} message: {
Text("iOSの設定でカメラへのアクセスを許可してください。")
}
}
func checkCamera() {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if status == AVAuthorizationStatus.authorized {
// print("アクセス許可あり")
} else if status == AVAuthorizationStatus.denied {
// print("アクセス許可されていない")
AVCaptureDevice.requestAccess(for: .video, completionHandler: { granted in
if (granted == false) {
showAlert = true
}
})
}
}
}