I want to remove all pending local notifications if the user removed notification permissions. Therefore, I wrote a function to check if permissions are given. If the permissions are given, schedule a random notification. If not, remove all pending notifications.
However, if the user opens the app once without permissions and then gives permissions again, the notification count jumps back to the same as before notifications were disabled. It seems like removeAllPendingNotificationRequests
does not have any effect if the user removed permissions as the notification count is always 0, although it isn’t. Overall, it seems like editing/adding/removing notifications without permission is not possible.
So how can I make sure that once the user gives notification permissions again, no notifications are delivered as long as the user hasn’t reopened the app to schedule new ones?
Example
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, world!")
}
.padding()
.task {
let nots = await UNUserNotificationCenter.current().pendingNotificationRequests()
if await notificationsAllowed() {
// is not 0 if the user had deactivated the notifications once
print("(nots.count) notifications scheduled")
let content = UNMutableNotificationContent()
content.title = "Hello"
content.body = "This is a notification"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
try? await UNUserNotificationCenter.current().add(request)
} else {
// always 0
print("(nots.count) notifications scheduled")
// does nothing
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
}
}
func notificationsAllowed() async -> Bool {
return await withCheckedContinuation { continuation in
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { success, _ in
continuation.resume(returning: success)
}
}
}
}