LoginSignup
67
26

More than 1 year has passed since last update.

iOS 14からUNNotificationPresentationOptionsの「.alert」が「.banner」と「.list」に分かれた

Last updated at Posted at 2020-09-29

はじめに

プッシュ通知の表示オプション( UNNotificationPresentationOptions )に .alert がありますが、iOS 14 から非推奨になりました。
代わりに .banner.list の2つに分かれ、これらの挙動を調べたので紹介します。

環境

  • Xcode:12.0 (12A7209)
  • Swift:5.3
  • iOS:14.0

プッシュ通知の挙動

以下の表の通りです。

.alert ではバナーと通知センターの両方に通知が来ましたが、iOS 14からは .banner.list を使うことでどちらか片方のみに通知が来るようにできます。

UNNotificationPresentationOptions バナー 通知センター
.alert Simulator Screen Shot - iPhone SE (2nd generation) - 2020-09-29 at 13.56.50.png Simulator Screen Shot - iPhone SE (2nd generation) - 2020-09-29 at 13.56.34.png
.banner Simulator Screen Shot - iPhone SE (2nd generation) - 2020-09-29 at 13.56.50.png Simulator Screen Shot - iPhone SE (2nd generation) - 2020-09-29 at 13.57.48.png
.list Simulator Screen Shot - iPhone SE (2nd generation) - 2020-09-29 at 13.58.49.png Simulator Screen Shot - iPhone SE (2nd generation) - 2020-09-29 at 13.56.34.png

実装

iOS 13以前も引き続き対応する場合、OSのバージョンで分岐させるのがベターです。

AppDelegate.swift
extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if #available(iOS 14.0, *) {
            completionHandler([.banner, .list, .sound])
        } else {
            completionHandler([.alert, .sound])
        }
    }
}

おまけ:シミュレータでプッシュ通知を試す

iOSのシミュレータにプッシュ通知を送るのは、以下の記事が役立ちました。
https://qiita.com/koogawa/items/85c0dd0abd2f1970c5fc

こちらの記事のおかげで、プッシュ通知をかんたんに送って試すことができました。

おわりに

iOS 14からは通知の表示を細かく制御できるようになったことがわかりました。
.list のみ指定することでAndroidのサイレント通知のように使えたりと、使いこなせると便利そうです。

もし便利な使いみちがありましたら、コメントなどで教えていただけると嬉しいです :relaxed:

参考リンク

67
26
1

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
67
26