Hi,
I'm triggering a notification from the audio interruption handler (but also have a debug button set to trigger it manually) and it frequently does not show up. I don't think I have ever seen it show up when the watch face is off.
I have created a singleton class to trigger this notification as follows. Note that I use a UUID in the identifier because an old thread here suggests this is necessary, but it makes no difference as far as I can tell.
Any ideas? I'd like this notification to be reliable. I'm also surprised that with trigger set to nil, it does not trigger instantaneously.
Any help would be much appreciated!
Thanks,
-- B.
import Foundation
import UserNotifications
class NotificationSender: NSObject, UNUserNotificationCenterDelegate {
static let shared = NotificationSender()
override init() {
super.init()
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.sound, .badge]) { granted, error in
if granted {
print("Notification permission granted")
} else {
print("Notification permission denied")
}
}
center.delegate = self
// Define the action to open the app
let openAction = UNNotificationAction(identifier: "openAction", title: "Open App", options: [.foreground])
// Add the action to the notification content
let category = UNNotificationCategory(identifier: "resumeAudioCategory", actions: [openAction], intentIdentifiers: [], options: [])
center.setNotificationCategories([category])
}
func sendNotification() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Recording Interrupted"
content.body = "You will need to restart it manually."
content.categoryIdentifier = "resumeAudioCategory"
// Create the notification request
//let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "ResumeAudioNotification-\(UUID().uuidString)", content: content, trigger: nil)
center.add(request) { error in
if let error = error {
print("Error adding notification request: \(error)")
}
}
}
// Handle notification when the app is in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Display the notification while the app is in the foreground
completionHandler([.sound, .badge, .banner, .list])
}
// Handle notification response
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Handle the user's response to the notification
// For example, navigate to a specific screen in your app
completionHandler()
}
}