0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】設定のカメラがOFFの場合に設定へ移動するアラート

Posted at

前提

  • 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
                }
            })
        }
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?