[iPhone] TimeInterval を使ったローカル通知

通知を発行するケースでサーバーを使ったRemoteで通知をユーザーに出す場合と、例えばタイマーやアラームなどのアプリがローカルに発行する場合があります。Time Intervalで繰り返しの通知を発行させてみます。


Swift 5.1
Xcode 11.4.1

UserNotifications

通知を発行するトリガーとして以下のものがあり、PushがRemote Notificationと言われていたものです。残りはローカル通知になります。

タイマーアプリを作るときはこの Time Interval が使いやすいでしょう。

サンプルコード

バックグラウンドで時間計測させたり、他のアプリを使っている時にも通知を出させるためにAppDelegateで設定します。

AppDelegate.swift

ViewController.swift


Time Intervalの通知を設定・削除するためにボタンを作ってstoryboardで紐付けしてください。
繰り返しの通知は60sec以上である必要があります。os_logを使っているのは時間を確認するためだけです。



References:
UserNotifications | Apple Developer Documentation
UNTimeIntervalNotificationTrigger — UserNotifications | Apple
UNUserNotificationCenter — UserNotifications | Apple
UNMutableNotificationContent — UserNotifications | Apple