ローカル通知を設定
viewController.swift
import UserNotification
//通知のタイトルと内容を設定
let content = UNMutableNotificationContent()
content.title = "(タイトル)"
content.body = "(内容)"
content.sound = UNNotificationSound.default() //通知音
//通知する日付を設定
let date:Date = (通知したい日付)
let calendar = Calendar.current()
let dateComponent = calendar.dateComponents([.year, .month, .day, .hour, minute] , from: date)
//以上の通知をリクエストに指定
let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponent, repeats: false)
let request = UNNotificationRequest.init(identifier: "一意の値", content: content,//UNMutableNotificationContent trigger: trigger //UNNotificationTrigger)
//通知を設定
let center = UNNotificationCenter.current()
center.add(request, completion: nil)
ユーザーへローカル通知の許諾の通知
AppDelegate.swift
import UserNotification
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert,.sound]){(granted, error) in
}
center.delegate = self;
return true
}
またアプリ起動中でもローカル通知を表示させるためのコード
AppDelegate.swift
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound, .alert])
}