アラートテンプレ集(コピペおけ)

実際によく使う順にアラート(UIAlertController)のテンプレをご用意しました。最後の全体コードをあなたのXcodeプロジェクトに新しくswiftファイルを作ってコピペすれば、すぐにご利用頂けます。

## 目次
[タスク完了アラート](#タスク完了アラート)
[エラー発生アラート](#エラー発生アラート)
[短文説明アラート](#短文説明アラート)
[二択(はいorいいえ)アラート](#二択アラート)
[入力欄付きアラート](#入力欄付きアラート)
[文字数オーバーアラート](#文字数オーバーアラート)
[入力破棄して画面巻き戻しアラート](#入力破棄して画面巻き戻しアラート)
[全体コード](#全体コード)

## タスク完了アラート
```swift:AlertExtension.swift
static func taskDoneAlert(taskString: String, viewController: UIViewController, completion: (() -> Void)?) {
        let alert = UIAlertController(title: "\(taskString)完了", message: "", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { action in
            completion?()
        }
        alert.addAction(okAction)
        viewController.present(alert, animated: true)
    }
```

使用例↓
```swift:SampleViewController.swift
UIAlertController.taskDoneAlert(taskString: "保存", viewController: self) {
            print("保存できましためでたしめでたし")
        }
```
![Simulator Screenshot - iPhone 15 Pro Max - 2023-11-12 at 23.53.52.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3578066/5b76a93a-b748-ae16-b724-286d9b9ecb15.png)

## エラー発生アラート
```swift:AlertExtension.swift
static func errorAlert(viewController: UIViewController) {
        let alert = UIAlertController(title: "エラー", message: "お手数ですがやり直してみてください\n申し訳ございません", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default)
        alert.addAction(okAction)
        viewController.present(alert, animated: true)
    }
```

![Simulator Screenshot - iPhone 15 Pro Max - 2023-11-13 at 00.23.03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3578066/e7114a84-0cbf-e3e5-d09a-68993f16002f.png)
catch文とかでエラー起きたときに使ってます。


## 短文説明アラート
```swift:AlertExtension.swift
static func simpleDescriptionAlert(title: String, message: String, viewController: UIViewController) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default)
        alert.addAction(ok)
        viewController.present(alert, animated: true)
    }
```

使用例↓
```swift:SampleViewController.swift
UIAlertController.simpleDescriptionAlert(title: "お問い合わせ先", message: "090-1234-5678", viewController: self)
```
![Simulator Screenshot - iPhone 15 Pro Max - 2023-11-13 at 00.25.09.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3578066/9b311bbc-52cf-aec6-9d48-dd090ab9185c.png)

表示後に特に何も処理を走らせず、ただ説明だけしたいときによく使います。


## 二択アラート
```swift:AlertExtension.swift
static func yesOrNoAlert(alertTitle: String, alertMessage: String, viewController: UIViewController, yesAlertStyle: UIAlertAction.Style,
yesCompletion: ( @escaping () -> Void), noCompletion: ( @escaping () -> Void) ) {

        let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
        let yes = UIAlertAction(title: "はい", style: yesAlertStyle) { _ in
            yesCompletion()
        }
        let no = UIAlertAction(title: "いいえ", style: .cancel) { _ in
            noCompletion()
        }
        alert.addAction(yes)
        alert.addAction(no)
        viewController.present(alert, animated: true)
    }
```

使用例↓
```swift:SampleViewController.swift
UIAlertController.yesOrNoAlert(alertTitle: "利用規約を開きますか？", alertMessage: "",
viewController: self, yesAlertStyle: .default) {
            print("ここに規約を開く処理")
        } noCompletion: {
            print("ここに規約を開かない場合の処理")
        }
```
![Simulator Screenshot - iPhone 15 Pro Max - 2023-11-13 at 00.25.00.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3578066/d385ab3c-7e54-278c-e676-5cc694b07bde.png)


## 入力欄付きアラート
```swift:AlertExtension.swift
static func textFieldAlert(alertTitle: String, alertMessage: String, placeholderText: String,
keyboardType: UIKeyboardType, doneButtonTitle: String, viewController: UIViewController, completion: ( @escaping (String) -> Void)) {

        let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.placeholder = placeholderText
            textField.keyboardType = keyboardType
        }
        let done = UIAlertAction(title: doneButtonTitle, style: .default) { _ in
            guard let textField = alert.textFields?.first, let inputText = textField.text else { return }
            if inputText == "" {
                UIAlertController.errorAlert(viewController: viewController)
            } else {
                completion(inputText)
            }
        }
        let cancel = UIAlertAction(title: "キャンセル", style: .cancel)
        alert.addAction(done)
        alert.addAction(cancel)
        viewController.present(alert, animated: true)
    }
```

使用例↓
```swift:SampleViewController.swift
UIAlertController.textFieldAlert(alertTitle: "通報しますか？", alertMessage: "何があったか入力してください", placeholderText: "",
keyboardType: .default, doneButtonTitle: "送信", viewController: self) { text in
            print("ここに入力欄の値textをどこかしらに送信する処理")
        }
```
![Simulator Screenshot - iPhone 15 Pro Max - 2023-11-13 at 00.25.57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3578066/7bf65fa8-e124-ea53-c095-8e75efed9697.png)

SNSなどユーザー同士でコミュニケーションとれるアプリで実装しないとAppStoreの審査に引っかかってしまうので、よくこのアラートを通報機能として使ってます。

keyboardTypeに.numberPadを指定すれば、画面遷移直前にユーザーに暗証番号を入力してもらうという使い方もできます。

## 文字数オーバーアラート
```swift:AlertExtension.swift
static func wordCoundOverAlert(wordLimit: Int, viewController: UIViewController) {
        let alert = UIAlertController(title: "\(wordLimit)字までしか\n入力できません", message: "", preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default)
        alert.addAction(ok)
        viewController.present(alert, animated: true)
    }
```

使用例↓
```swift:SampleViewController.swift
UIAlertController.wordCoundOverAlert(wordLimit: 1000, viewController: self)
```
![Simulator Screenshot - iPhone 15 Pro Max - 2023-11-13 at 00.27.27.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3578066/792c93ff-bb89-6a06-70db-4d1090fa104e.png)


## 入力破棄して画面巻き戻しアラート
```swift:AlertExtension.swift
static func checkBackAlert(task: String, viewController: UIViewController) {
        let alert = UIAlertController(title: "戻りますか？", message: "\(task)は破棄されます", preferredStyle: .alert)
        let yes = UIAlertAction(title: "はい", style: .destructive) { _ in
            viewController.navigationController?.popViewController(animated: true)
        }
        let no = UIAlertAction(title: "いいえ", style: .cancel)
        alert.addAction(yes)
        alert.addAction(no)
        viewController.present(alert, animated: true)
    }
```

使用例↓
```swift:SampleViewController.swift
UIAlertController.checkBackAlert(task: "入力内容", viewController: self)
```
![Simulator Screenshot - iPhone 15 Pro Max - 2023-11-13 at 00.27.40.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3578066/2a82b4c3-e39e-823f-c801-202845b8cfdd.png)

入力された内容が保存されていないのにUINavigationControllerで前の画面に戻ろうとしている時に使っています。navigationItem.leftBarButtonItemに新しくキャンセルボタンを作っておいて、タップしたときに入力内容が保存されていない場合このメソッドを呼び出します。

削除が関わる選択なので、UIAlertActionのstyleを.destructiveにして赤くしています


# 全体コード
```swift:AlertExtension.swift
import UIKit

extension UIAlertController {

    static func taskDoneAlert(taskString: String, viewController: UIViewController, completion: (() -> Void)?) {
        let alert = UIAlertController(title: "\(taskString)完了", message: "", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { action in
            completion?()
        }
        alert.addAction(okAction)
        viewController.present(alert, animated: true)
    }

    
    static func errorAlert(viewController: UIViewController) {
        let alert = UIAlertController(title: "エラー", message: "お手数ですがやり直してみてください\n申し訳ございません", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default)
        alert.addAction(okAction)
        viewController.present(alert, animated: true)
    }
    
    
    static func simpleDescriptionAlert(title: String, message: String, viewController: UIViewController) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default)
        alert.addAction(ok)
        viewController.present(alert, animated: true)
    }
    
    
    static func yesOrNoAlert(alertTitle: String, alertMessage: String, viewController: UIViewController, yesAlertStyle: UIAlertAction.Style, 
    yesCompletion: ( @escaping () -> Void), noCompletion: ( @escaping () -> Void) ) {
    
        let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
        let yes = UIAlertAction(title: "はい", style: yesAlertStyle) { _ in
            yesCompletion()
        }
        let no = UIAlertAction(title: "いいえ", style: .cancel) { _ in
            noCompletion()
        }
        alert.addAction(yes)
        alert.addAction(no)
        viewController.present(alert, animated: true)
    }

    
    static func textFieldAlert(alertTitle: String, alertMessage: String, placeholderText: String,
    keyboardType: UIKeyboardType, doneButtonTitle: String, viewController: UIViewController, completion: ( @escaping (String) -> Void)) {
    
        let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.placeholder = placeholderText
            textField.keyboardType = keyboardType
        }
        let done = UIAlertAction(title: doneButtonTitle, style: .default) { _ in
            guard let textField = alert.textFields?.first, let inputText = textField.text else { return }
            if inputText == "" {
                UIAlertController.errorAlert(viewController: viewController)
            } else {
                completion(inputText)
            }
        }
        let cancel = UIAlertAction(title: "キャンセル", style: .cancel)
        alert.addAction(done)
        alert.addAction(cancel)
        viewController.present(alert, animated: true)
    }

    
    static func wordCoundOverAlert(wordLimit: Int, viewController: UIViewController) {
        let alert = UIAlertController(title: "\(wordLimit)字までしか\n入力できません", message: "", preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default)
        alert.addAction(ok)
        viewController.present(alert, animated: true)
    }

    
    static func checkBackAlert(task: String, viewController: UIViewController) {
        let alert = UIAlertController(title: "戻りますか？", message: "\(task)は破棄されます", preferredStyle: .alert)
        let yes = UIAlertAction(title: "はい", style: .destructive) { _ in
            viewController.navigationController?.popViewController(animated: true)
        }
        let no = UIAlertAction(title: "いいえ", style: .cancel)
        alert.addAction(yes)
        alert.addAction(no)
        viewController.present(alert, animated: true)
    }
    
}
```