概要
業務でローカル通知を実装したので忘れないように備忘録です。
環境はXcode15、swift5.9です。
Swift Concurrencyが用意されているので利用します。
ローカル通知クラスの実装
import Foundation
import UserNotifications
final class LocalNotification {
public static let shared = LocalNotification()
func scheduleNotificationIfAuthorized() async throws {
do {
if try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) {
let content = UNMutableNotificationContent()
content.title = "アプリ名"
content.body = "コメント"
var dateComponents = DateComponents()
dateComponents.weekday = 6 // 土曜日
dateComponents.hour = 19 //19時
dataComponents.minute = 15 // 15分
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
try await UNUserNotificationCenter.current().add(request)
}
} catch {
throw ModelError.localNotification
}
}
}
AppDelegateで呼び出し
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Task {
try await LocalNotification.shared.scheduleNotificationIfAuthorized()
}
...
}
}
...
Capabilitiesに追加
CapabilitiesにPush Notificationsを追加して完了です。
こちらで実装できるかなと思います。