困っていること
表題の通りSwiftUIでpermissionの判定をして、もし許可されていない場合ダイアログを表示させて設定画面に飛ばすような挙動を実装したいとかんがえているのですがどう実装して良いのかわからず困っています。
試したこと
調べているとCombineで実装している以下のような記事があったので参考にしてみたのですが、アラートがうまく表示されませんでした
https://stackoverflow.com/questions/62561308/swiftui-direct-a-user-to-their-settings-page-if-authorizationstatus-is-denied
試したコード
Swift
struct CustomView: View { @ObservedObject var microphoneAutholization = MicrophoneAutholization() var body: some View { Rectangle() .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) .foregroundColor(Color.clear) .gesture(LongPressGesture().onChanged { _ in if !isMicrophoneAuthorizationApproved() { return } isRecording = true }) .alert(isPresented: self.$microphoneAutholization.invalidPermission) { Alert( title: Text("TITLE"), message: Text("Please go to Settings and turn on the permissions"), primaryButton: .cancel(Text("Cancel")), secondaryButton: .default(Text("Settings"), action: { if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } })) } } private func isMicrophoneAuthorizationApproved() -> Bool { let status = AVCaptureDevice.authorizationStatus(for: .audio) switch status { case .authorized: return true default: return false } } } import Combine import AVFoundation class MicrophoneAutholization: ObservableObject { @Published var invalidPermission: Bool = false var authorizationStatus: AnyPublisher< AVAuthorizationStatus, Never> { Future<AVAuthorizationStatus, Never> { promise in let status = AVCaptureDevice.authorizationStatus(for: .audio) promise(.success(status)) } .eraseToAnyPublisher() } func requestAccess() { self.authorizationStatus .receive(on: RunLoop.main) .map { $0 == .denied || $0 == .notDetermined || $0 == .restricted } .assign(to: .invalidPermission, on: self) } }
解決したいこと
今回無理にCombineを理解しようとは思っておらずCombineを使わなくても実装かのうなのであればそちらで実装したいと考えています
まだ回答がついていません
会員登録して回答してみよう