Untitled
unknown
plain_text
a year ago
3.5 kB
7
Indexable
import Foundation
import UserNotifications
class NotificationManager {
static let shared = NotificationManager()
private init() {}
enum RepeatInterval {
case none
case daily
case weekly
case monthly
case everyTwoDays
}
func requestNotificationPermission(completion: @escaping (Bool) -> Void) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
DispatchQueue.main.async {
completion(success)
}
if let error = error {
print("Error requesting permission: \(error.localizedDescription)")
}
}
}
func scheduleNotification(title: String, body: String, date: Date, identifier: String, repeatInterval: RepeatInterval = .none) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default
let trigger: UNCalendarNotificationTrigger
switch repeatInterval {
case .none:
let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
case .daily:
let triggerDate = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
case .weekly:
let triggerDate = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date)
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
case .monthly:
let triggerDate = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: date)
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
case .everyTwoDays:
let interval = TimeInterval(2 * 24 * 60 * 60)
trigger = UNCalendarNotificationTrigger(dateMatching: Calendar.current.dateComponents([.hour, .minute, .second], from: date), repeats: true)
}
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error scheduling notification: \(error.localizedDescription)")
} else {
print("Notification scheduled for \(date) with repeat interval: \(repeatInterval)")
}
}
}
func scheduleMultipleNotifications(notifications: [(title: String, body: String, date: Date, identifier: String, repeatInterval: RepeatInterval)]) {
for notification in notifications {
scheduleNotification(
title: notification.title,
body: notification.body,
date: notification.date,
identifier: notification.identifier,
repeatInterval: notification.repeatInterval
)
}
}
func cancelNotification(identifier: String) {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
}
func cancelAllNotifications() {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
}
Editor is loading...
Leave a Comment