Meshtastic-Apple/Meshtastic/Helpers/LocalNotificationManager.swift

80 lines
2.4 KiB
Swift
Raw Normal View History

2021-10-06 17:51:52 -07:00
import Foundation
import SwiftUI
2024-06-03 02:17:55 -07:00
import OSLog
class LocalNotificationManager {
var notifications = [Notification]()
2021-11-29 15:59:06 -08:00
// Step 1 Request Permissions for notifications
2021-11-29 15:59:06 -08:00
private func requestAuthorization() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted == true && error == nil {
self.scheduleNotifications()
}
}
}
2021-11-29 15:59:06 -08:00
func schedule() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
case .notDetermined:
self.requestAuthorization()
case .authorized, .provisional:
self.scheduleNotifications()
default:
break // Do nothing
}
}
}
2021-11-29 15:59:06 -08:00
// This function iterates over the Notification objects in the notifications array and schedules them for delivery in the future
2021-11-29 15:59:06 -08:00
private func scheduleNotifications() {
for notification in notifications {
2024-01-20 14:05:29 -08:00
let content = UNMutableNotificationContent()
content.subtitle = notification.subtitle
content.title = notification.title
content.body = notification.content
content.sound = .default
content.interruptionLevel = .timeSensitive
if notification.target != nil {
content.userInfo["target"] = notification.target
}
2024-01-20 14:05:29 -08:00
if notification.path != nil {
content.userInfo["path"] = notification.path
2024-01-20 14:05:29 -08:00
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: notification.id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error {
Logger.services.error("Error Scheduling Notification: \(error.localizedDescription)")
}
}
}
}
2021-11-29 15:59:06 -08:00
// Check and debug what local notifications have been scheduled
2021-11-29 15:59:06 -08:00
func listScheduledNotifications() {
UNUserNotificationCenter.current().getPendingNotificationRequests { notifications in
for notification in notifications {
2024-06-23 16:11:02 -07:00
Logger.services.debug("\(notification, privacy: .public)")
}
}
}
2021-11-29 15:59:06 -08:00
}
struct Notification {
var id: String
var title: String
var subtitle: String
var content: String
var target: String?
2024-01-20 14:05:29 -08:00
var path: String?
}