【Swift5】ローカル通知(UNUserNotificationCenter)の最大登録数について

UILocalNotification は使ったことあるのですが、3年ほど前は最大登録数は64でした。
iOS10 で非推奨になっても実装アプリは動くんで、アップデートも先延ばしになってたりして、UNUserNotificationCenter はまだ実装した事がなかったので、ちょっと調べてみました。

検証

UNUserNotificationCenter を使って通知を100個登録。
for文で回して1秒毎に通知が来るよう登録して、通知のメッセージ部分に「Notification 番号」が表示されるようにしました (-ω-ゞ

override func viewDidLoad() {
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
        guard granted else {
            return
        }
        for i in 1...100 {
            let content = UNMutableNotificationContent()
            content.title = "Test"
            content.body = "Notification \(i)"
            content.sound = .none
            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: TimeInterval(1 + (1 * i)), repeats: false)
            let request = UNNotificationRequest.init(identifier: "identifier-\(i)", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request)
        }
    }
}

これを実行すると、通知センターにはこう表示されました。

見づらくて申し訳ないのですが、赤線の部分に「63 more notifications」とあります。
表示されてる通知+その他の63個の通知なので、64個通知が登録されてた事になります。

そんでもう1つ、メッセージ部分が「Notification 100」となってます。
通知センターを一番下にスクロールすると…

「Notification 37」から受信してるので、1〜36までの通知は上書きされてることになります。
上限の64に対して、UNUserNotificationCenter は古い通知が削除されて、新しい通知が登録されるので、管理に気をつけないといけないですね (ー∀ー;

登録した通知を管理する

登録した通知を取得する

UNUserNotificationCenter.current().getPendingNotificationRequests { notifications in
    for notification in notifications {
        print(notification)
    }
}

登録した通知を削除する

// 通知を全削除する
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

// 指定した通知を削除する
let identifiers = ["identifier-1", "identifier-10", "identifier-100"]
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)

さいごに

目覚ましアプリで1週間とか暫くしたら鳴らなくなるのって、これが原因じゃないかなって思ってます (´-ω-`)
全て登録に使うのではなく、1つは起動を促すような通知に使う方がいいですね。

違うよ!とかこういう方法あるよ!ってのがあれば教えてください。
では( ¯·ω·¯ )

Swift
スポンサーリンク

コメント