Swiftコード内で時間指定して通知を表示するローカル通知関連のメモです。
尚、外部からの通信で発火するプッシュ通知は本ページでは取り扱いません。
環境
Swift5.4
Xcode12.4
Storyboard
ユーザーに通知許可を求める
Swift
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { (_, _) in})
◯秒後に通知を表示する
UNUserNotificationCenterDelegateをViewControllerに承継させる必要があります。
Swift
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "通知のタイトル"
notificationContent.subtitle = "通知のサブタイトル"
notificationContent.body = "通知の本文"
notificationContent.sound = .default
notificationContent.badge = 1 //バッチをアプリアイコンにつける場合は必要。バッチの数字を指定。
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 900, repeats: false) //ここでtimeIntervalに秒数を指定
let request = UNNotificationRequest(identifier: "notice id", content: notificationContent, trigger: notificationTrigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request, withCompletionHandler: nil)
notificationCenter.delegate = self
毎日指定した時間に通知する
UNUserNotificationCenterDelegateをViewControllerに承継させる必要があります。
Swift
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "通知のタイトル"
notificationContent.subtitle = "通知のサブタイトル"
notificationContent.body = "通知の本文"
notificationContent.sound = .default
notificationContent.badge = 1 //バッチをアプリアイコンにつける場合は必要。バッチの数字を指定。
let noticeTime = DateComponents(hour: 16)//ここで時間指定。左記は16:00。オーバーロードの選択でナノ秒まで指定可能。
let notificationTrigger = UNCalendarNotificationTrigger.init(dateMatching: noticeTime, repeats: true)
let request = UNNotificationRequest.init(identifier: "notice id", content: notificationContent, trigger: notificationTrigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request)
notificationCenter.delegate = self
登録した通知をキャンセルする
Swift
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removePendingNotificationRequests(withIdentifiers: ["notice id"])
通知でつけたバッジを削除する
Swift
UIApplication.shared.applicationIconBadgeNumber = 0