Untitled

 avatar
unknown
plain_text
5 months ago
2.4 kB
5
Indexable
import SwiftUI
import UserNotifications

@main
struct LocalNotificationsDemoApp: App {
    let notificationDelegate = NotificationDelegate()

    init() {
        UNUserNotificationCenter.current().delegate = notificationDelegate

        requestNotificationPermissionAndSchedule()
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
    
    // Request permission and schedule notifications
    private func requestNotificationPermissionAndSchedule() {
        NotificationManager.shared.requestNotificationPermission { granted in
            if granted {
                let notifications = [
                    (title: "Daily Reminder", body: "The notification will repeat daily at 8:00 AM", date: Calendar.current.date(bySettingHour: 8, minute: 0, second: 0, of: Date())!, identifier: "daily_reminder", repeatInterval: .daily),
                    (title: "Weekly Reminder", body: "It will repeat weekly at 9:00 AM on the same day of the week as the initial scheduling date.", date: Calendar.current.date(bySettingHour: 9, minute: 0, second: 0, of: Date())!, identifier: "weekly_reminder", repeatInterval: .weekly),
                    (title: "Monthly Reminder", body: "It will repeat monthly at 10:00 AM on the same day of each month as the initial scheduling date.", date: Calendar.current.date(bySettingHour: 10, minute: 0, second: 0, of: Date())!, identifier: "monthly_reminder", repeatInterval: .monthly),
                    (title: "Every Two Days", body: "It will repeat every two days at the same time when it was first scheduled", date: Calendar.current.date(byAdding: .day, value: 2, to: Date())!, identifier: "every_two_days_reminder", repeatInterval: NotificationManager.RepeatInterval.everyTwoDays)
                ]
                
                NotificationManager.shared.scheduleMultipleNotifications(notifications: notifications)
                print("Scheduled multiple notifications")
            } else {
                print("Notification permission not granted")
            }
        }
    }
}

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.banner, .sound])
    }
}
Editor is loading...
Leave a Comment