1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

スケジューリングされたローカル通知実装

Last updated at Posted at 2024-01-28

概要

業務でローカル通知を実装したので忘れないように備忘録です。
環境は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を追加して完了です。

こちらで実装できるかなと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?