Meshtastic-Apple/Meshtastic/Helpers/LocalNotificationManager.swift
Blake McAnally 4d547e48db This change fixes several lint errors throughout the project, and moves the SwiftLint build phase to before compilation.
After this change, a developer can now clone the project and run without the build failing due to lint errors! 😃

* I ran `swiftlint --fix` to resolve many auto-correctable issues (mostly whitespace)
* Excluded the `Meshtastic/Protobufs` directory from lint, since that code is automatically generated.
* Converted some single letter method parameters to lowercase.
* Converted several instances `force_cast` to instead use `guard` or `if let` to unwrap optional values. During this change, some of the SwiftUI views became "too complex to be solved in a reasonable time", so I broke up the views into distinct sub-expressions.

I was able to build and run the app on an iOS simulator.
2024-05-31 21:48:50 -05:00

77 lines
2.3 KiB
Swift

import Foundation
import SwiftUI
class LocalNotificationManager {
var notifications = [Notification]()
// Step 1 Request Permissions for notifications
private func requestAuthorization() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted == true && error == nil {
self.scheduleNotifications()
}
}
}
func schedule() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
case .notDetermined:
self.requestAuthorization()
case .authorized, .provisional:
self.scheduleNotifications()
default:
break // Do nothing
}
}
}
// This function iterates over the Notification objects in the notifications array and schedules them for delivery in the future
private func scheduleNotifications() {
for notification in notifications {
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
}
if notification.path != nil {
content.userInfo["path"] = notification.path
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: notification.id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
guard error == nil else { return }
}
}
}
// Check and debug what local notifications have been scheduled
func listScheduledNotifications() {
UNUserNotificationCenter.current().getPendingNotificationRequests { notifications in
for notification in notifications {
print(notification)
}
}
}
}
struct Notification {
var id: String
var title: String
var subtitle: String
var content: String
var target: String?
var path: String?
}