えむじぃのアプリ開発

えむじぃのアプリ開発

元大手IT企業SE、現ベンチャー企業CTOのブログです。

【Swift】UNNotificationRequestでローカル通知を行う

今回はUNNotificationRequestでローカル通知を行う方法をこの記事で説明します。

この記事のポイント・UNNotificationRequestを使用

ローカル通知を行う方法

UNNotificationRequestでローカル通知を行う場合は以下のように設定します。

----------------------------------------------------
// Local Notification Start
// 直接日時を設定
let triggerDate = DateComponents(month:MM, day:DD, hour:Int(setHH), minute:Int(setmm), second: 00)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
   
// 通知コンテンツの作成
let content = UNMutableNotificationContent()
content.title = "お知らせ。"
content.body = "今日は打ち合わせの日です。"
content.sound = UNNotificationSound.default

// 通知リクエストの作成
request = UNNotificationRequest.init(
     identifier: "CalendarNotification",
     content: content,
     trigger: trigger)
 
// 通知リクエストの登録
let center = UNUserNotificationCenter.current()
center.add(request)

// Local Notification End
----------------------------------------------------

これで指定した日時にローカル通知が行われます。