[iPhone] CalendarNotification 日付け時刻を指定して通知する

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


Swift 5.1
Xcode 11.4.1

UserNotifications

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

めざまし時計アプリを作るときはこの Calendar を使ったほうがいいでしょう。

サンプルコード

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

AppDelegate.swift

ViewController.swift

 

現在の時刻から1分後に設定するケース

 

日付フォーマットでのja_JPおけるスタイル;

dateStyle
.full 2020年4月26日日曜日
.long 2020年4月26日
.medium 2020/04/26
.short 2020/04/26
.none (出力なし)
timeStyle
.full 21時06分10秒 日本標準時
.long 21:06:10 JST
.medium 21:06:10
.short 21:06
.none (出力なし)

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