通知の設定
InfoHelperに以下のメソッドを追加します。
func setNotification(_ item:TodoItem){
let targetDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute],from: item.date)
let trigger = UNCalendarNotificationTrigger(dateMatching: targetDate,repeats: false)
let content = UNMutableNotificationContent()
content.title = item.title
content.sound = .default
let request = UNNotificationRequest(identifier: item.id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
解説
let targetDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute],from: item.date)
let trigger = UNCalendarNotificationTrigger(dateMatching: targetDate,repeats: false)
1行目 item.dateから年、月、時間、分のデータを取得します。
2行目 取得した日時からUNCalendarNotificationTriggerインスタンスを作成します。
let content = UNMutableNotificationContent()
content.title = item.title
content.sound = .default
let request = UNNotificationRequest(identifier: item.id, content: content, trigger: trigger)
1~3行目 通知の内容を管理するUNMutableNotificationContentインスタンスを作成します。
4行目 id、表示内容、時刻からUNNotificationRequestインスタンスを作成します。
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
UNNotificationRequestインスタンスを使用して通知の予約をします。
AppDelegateの編集
import UIKit
import UserNotifications
@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options:[.alert,.sound,.badge]){
(granted, error) in
}
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification,withCompletionHandler completionHandler:@escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner,.sound])
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
コメント