I've made a simple test app that schedules a notification for 5 seconds later, and checks to see that it's scheduled, and although this code works in iOS (shows a notification after 5 seconds) it does not on Apple Watch. I'm wondering what more I have to do or add to have these notifications successfully delivered and seen.
import SwiftUI
import UserNotifications
struct ContentView: View {
@State var numberOfRequests = 0
var body: some View {
VStack{
Button(
action: {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
},
label: { Text("Request") }
)
Button(
action: {
let content = UNMutableNotificationContent()
content.title = "Feed the cat"
content.subtitle = "It looks hungry"
content.sound = UNNotificationSound.default
content.categoryIdentifier = "myCategory"
// show this notification five seconds from now
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
},
label: { Text("Set notification") }
)
Button(
action: {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.getPendingNotificationRequests(completionHandler: { requests in
print("The are \(requests.count) requests!")
self.numberOfRequests = requests.count
}
)
},
label: { Text("Show notifications") }
)
Text("\(self.numberOfRequests)")
}
}
}