0
2

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 3 years have passed since last update.

マイクなどの使用許可が得られなかった時のことを考慮した話

Posted at

はじめに

 アプリの中でマイクやカメラを使うときは、「マイクの使用を許可しますか?」といったアラートが表示されます。そこでユーザーが誤って「許可しない」を選択した場合、ユーザーにそのことを伝えるにはどうすれば良いでしょうか。ここではその解決策を共有します。

流れ

ezgif-2-11aa8ab89fc0.gif

初めて許可を求める -> アラートを表示
許可されている場合 -> 何もアラートを表示させない
許可されていない場合 -> そのことをアラートで表示させる
といった処理をやっていきます。

 

ボタンが押された時

ここでは画面表示を担当するクラスでの動きを書いています。

@objc func startButtonTapped() {
        let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
        if status == AVAuthorizationStatus.authorized {
            startButton.isHidden = true
            pauseButton.isHidden = false
            
        } else if status == AVAuthorizationStatus.restricted {
            audioRequestDelegate?.showPermissionChangeAlert()
        } else if status == AVAuthorizationStatus.notDetermined {
            audioRequestDelegate?.requestPermission()
        } else if status == AVAuthorizationStatus.denied {
            audioRequestDelegate?.showPermissionChangeAlert()
        }
    }

上の関数は収録ボタンが押された時の動きを表す関数です。AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)でマイクの使用許可に関する値を判定しています。その後、値に応じて処理を分けています。

なおAVAuthorizationStatusは列挙型で

public enum AVAuthorizationStatus : Int {

    case notDetermined = 0

    case restricted = 1

    case denied = 2

    case authorized = 3
}

と定義されているのですが、case restricted = 1はほとんどとる値ではないことがリファレンスに書かれているので、その値を取ることを想定していません。

ボタンが押された時のコントローラーの動き

上のビュークラスから処理を委譲されたコントローラークラスの動きです。

extension RecordingViewController: AudioRequestDelegate{
    //許可を求めるアラートを出す
    func requestPermission() {
        recordingModel?.requestRecord()
    }
    //拒否されているので、設定し直すアラートを出す
    func showPermissionChangeAlert() {
        print("拒否されてます")
        let alert = UIAlertController(title: "マイクの許可", message: "設定からマイクの使用を許可してください", preferredStyle: .alert)
        let alertAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
        alert.addAction(alertAction)
        present(alert, animated: true, completion: nil)
    }
    //許可されている時
    func authorized() {
        recordingModel?.start()
    }
}

許可をされている時は録音をスタートし、まだ聞いていない時は確認アラートが表示されます。そして拒否されている時はUIAlertControllerを作成し、アラートでユーザに設定を変えることを伝えます。
許可が既に得られている場合とまだ許可を求めたことがない場合の処理はモデルクラスで定義したものを持ってきています。

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?