1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift5/Xcode】iOSでのローカル通知の実装方法まとめ

Last updated at Posted at 2021-03-25

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
1
2
0

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?