Swiftでローカル通知をユーザーに送りたい時に使うのが UNUserNotificationCenter.current().add() です。
アプリがバックグラウンドにあるときでも、決められた時刻やタイミングでユーザーに通知を届けることができる重要な機能です。
この記事では、基本的な意味や使い方、主要な引数の意味、注意点までわかりやすく解説します。
UNUserNotificationCenter.current().add() とは?
UNUserNotificationCenter.current().add() は UserNotificationsフレームワークにおけるメソッドで、ローカル通知をシステムに登録するためのものです。
「指定した条件(時刻や場所など)になったときにユーザーに通知を送る予約」をシステムに対して行うことができます。
具体例:時刻を指定したリマインダー通知
このサンプルコードは、ユーザーが設定した時刻にリマインダー通知を送る流れを示しています。
ボタンを押すと10秒後に通知が届き、アプリがバックグラウンドにあっても通知バナーが表示されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import SwiftUI import UserNotifications struct ContentView: View { @State private var notificationPermissionGranted = false @State private var notificationScheduled = false var body: some View { VStack(spacing: 20) { Text("ローカル通知のサンプル") .font(.title) Button("通知許可をリクエスト") { requestNotificationPermission() } Button("10秒後に通知を設定") { scheduleNotification() } .disabled(!notificationPermissionGranted) if notificationScheduled { Text("通知が設定されました!") .foregroundColor(.green) } } .onAppear { checkNotificationSettings() } } func requestNotificationPermission() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in DispatchQueue.main.async { self.notificationPermissionGranted = granted } } } func checkNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { settings in DispatchQueue.main.async { self.notificationPermissionGranted = settings.authorizationStatus == .authorized } } } func scheduleNotification() { // 通知の内容を設定 let content = UNMutableNotificationContent() content.title = "リマインダー" content.body = "設定した通知が届きました!" content.sound = .default content.badge = 1 // 10秒後に発火するトリガーを設定 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) // 通知リクエストを作成 let request = UNNotificationRequest( identifier: "reminder-notification", content: content, trigger: trigger ) // システムに通知を登録 UNUserNotificationCenter.current().add(request) { error in DispatchQueue.main.async { if error == nil { self.notificationScheduled = true } } } } } |
この例では、UNMutableNotificationContentで通知の内容を設定し、UNTimeIntervalNotificationTriggerで10秒後の発火条件を指定しています。
最終的に UNUserNotificationCenter.current().add() でシステムに通知を登録することで、アプリがバックグラウンドでも通知が届くようになります。
つまり、「通知内容の準備」→「発火条件の設定」→「システムへの登録」という一連の流れで通知機能を実装できるわけです。
UNUserNotificationCenter.current().add() はこの「システムへの登録」の役割を担っています。
主要な引数とその意味
UNUserNotificationCenter.current().add() を正しく使うには、UNNotificationRequestの構成要素を理解しておくことが重要です。
ここで紹介する要素を押さえておくと、通知の内容やタイミングを細かくコントロールできるようになります。
UNNotificationRequestを構成する主要な要素は次のとおりです。
要素名 | 型 | 説明 |
---|---|---|
identifier | String | 通知を識別するためのユニークなID |
content | UNMutableNotificationContent | 通知のタイトル、本文、音などの内容 |
trigger | UNNotificationTrigger? | 通知を発火させる条件(時間、場所など) |
UNMutableNotificationContentでは title(タイトル)、body(本文)、sound(通知音)、badge(バッジ数)などを設定できます。
triggerには UNTimeIntervalNotificationTrigger(時間間隔)、UNCalendarNotificationTrigger(特定の日時)、UNLocationNotificationTrigger(位置情報)などがあり、用途に応じて使い分けます。
これらの要素を理解することで、ユーザーに届ける通知のタイミングや内容を適切に設計できるようになります。
指定の仕方
上記の要素を組み合わせて UNNotificationRequest を作成し、add() メソッドに渡します。
これらを設定することで、どのタイミングで通知を出すか、どんな内容の通知にするか、通知後にどのような処理を行うかを決められます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// 通知の内容を設定 let content = UNMutableNotificationContent() content.title = "アプリ名" // 通知のタイトル content.body = "重要なお知らせがあります" // 通知の本文 content.sound = .default // 通知音(デフォルト音) content.badge = 1 // アプリアイコンのバッジ数 // 発火条件を設定(ここでは30分後) let trigger = UNTimeIntervalNotificationTrigger( timeInterval: 30 * 60, // 30分 = 30 * 60秒 repeats: false // 一回のみ ) // 通知リクエストを作成 let request = UNNotificationRequest( identifier: "important-reminder", // 通知の識別子 content: content, // 通知の内容 trigger: trigger // 発火条件 ) // システムに通知を登録 UNUserNotificationCenter.current().add(request) { error in if let error = error { print("通知登録エラー: \(error.localizedDescription)") } else { print("通知が正常に登録されました") } } |
ここで特に大切なのは identifier と trigger の指定です。
identifier は同じ通知を後から更新や削除する際に使用される重要な要素で、ユニークな文字列を設定する必要があります。
trigger は通知のタイミングを決める部分で、UNTimeIntervalNotificationTrigger以外にも特定の日時や曜日を指定できる UNCalendarNotificationTrigger などが使えます。
これらを正しく組み合わせることで、アプリに自然な形で通知機能を組み込めます。
UNUserNotificationCenter.current().add() の活用シーン
UNUserNotificationCenter.current().add() はアプリの中で「ユーザーに適切なタイミングで情報を届けたい」といったニーズに応えるために使われます。
- リマインダーアプリでの指定時刻での通知機能
- タスク管理アプリでの期限切れ前のアラート通知
- フィットネスアプリでの運動時刻や水分補給の促し通知
- 学習アプリでの復習タイミングのお知らせ機能
- ゲームアプリでのログインボーナスやイベント開始の告知通知
直感的なAPIで、複雑な通知スケジューリングを簡単に実装できる点が魅力です。
特に、ユーザーがアプリを閉じた後でも「決められたタイミングで情報を届ける」ことができる点が大きなメリットです。
UNUserNotificationCenter.current().add() を使うときの注意点
便利な UNUserNotificationCenter.current().add() ですが、使う際にはいくつかの前提条件や注意すべきポイントがあります。
- 通知許可(Authorization)をユーザーから事前に取得する必要がある
- import UserNotifications が必要
- 同じidentifierで複数回登録すると、古い通知は自動的に置き換えられる
- アプリが削除されると登録された通知もすべて削除される
つまり、UNUserNotificationCenter.current().add() を単体で使うだけではなく、必ず事前の許可取得と適切なエラーハンドリングを組み合わせて設計すること。
そして、ユーザーが通知を許可していない場合や、システム設定で通知がオフになっている場合も考慮することが実践的な利用には欠かせません。
まとめ
今回は Swift の UNUserNotificationCenter.current().add() について詳しく紹介しました。
- UNUserNotificationCenter.current().add() はローカル通知をシステムに登録するメソッド
- identifier、content(通知内容)、trigger(発火条件)の指定で挙動を制御
- リマインダーや期限通知など、タイミングを重視する機能で幅広く活用できる
- 事前の通知許可取得と適切なエラーハンドリングが必要
Swiftでローカル通知機能を実装する際には、UNUserNotificationCenter.current().add() を使うことでシステム標準の通知UIと連携した自然な通知体験を提供できます。
ぜひアプリの機能に組み込んでみてくださいね!