PUROGU LADESU

ポエムがメインのブログです。

【Swift】DispatchQueueの中でAlertを出す

何か処理をして終了時にポップアップさせる

DispatchQueue.global(qos: .userInitiated).async {

    // バックグラウンド処理を実行
    doSomething()

    // メインスレッドで処理
    DispatchQueue.main.async {
      let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
      alert.addAction(UIAlertAction(title: "OK", style: .default, handler: handler))
      viewc.present(alert, animated: true, completion: nil)
    }
}

単純なアラート

    static func simpleAlert(_ viewc: UIViewController, title: String, message: String, handler: ((UIAlertAction) -> Void)? = nil) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: handler))
        DispatchQueue.main.async {
            viewc.present(alert, animated: true, completion: nil)
        }
    }

単純な確認ダイアログ

    static func simpleConfirm(_ viewc: UIViewController, title: String, message: String, okHandler: ((UIAlertAction) -> Void)?, cancelHandler: ((UIAlertAction) -> Void)? = nil) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "はい", style: .default, handler: okHandler))
        alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: cancelHandler))
        DispatchQueue.main.async {
            viewc.present(alert, animated: true, completion: nil)
        }
    }