I am trying to retrieve delivered notifications using UNUserNotificationCenter.getDeliveredNotifications(completionHandler:), but I have encountered an issue:
Notifications triggered by UNTimeIntervalNotificationTrigger or UNCalendarNotificationTrigger appear in the delivered list. However, notifications triggered by UNLocationNotificationTrigger do not appear in the list. Here is the code I use to fetch delivered notifications:
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in for notification in notifications { print("Received notification: \(notification.request.identifier)") } }
The notification is scheduled as follows:
let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = "Test Notification" content.body = "This is a location-based notification." content.sound = .default let coordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194) // Example coordinates let region = CLCircularRegion(center: coordinate, radius: 100, identifier: "TestRegion") region.notifyOnEntry = true region.notifyOnExit = false let trigger = UNLocationNotificationTrigger(region: region, repeats: false) let request = UNNotificationRequest(identifier: "LocationTest", content: content, trigger: trigger) center.add(request) { error in if let error = error { print("Error adding notification: \(error.localizedDescription)") } }
Why does getDeliveredNotifications not return notifications that were triggered using UNLocationNotificationTrigger? How can I retrieve such notifications after they have been delivered?
Why does getDeliveredNotifications not return notifications that were triggered using UNLocationNotificationTrigger?
I believe this intentional behavior intended to protect user privacy. One of the "goals" of location based notifications is that they provide a way for an app to implement location based functionality in way that inherently has full user consent*. That works by posting the notification to the user when it's triggered by location but ONLY informing the app about that event when the user interacts with the notification. In concrete terms, if the user doesn't touch "tell the app I'm here" button, then your app never "knows" that the user was ever there.
*Note that this is why your app only needs WhenInUse authorization, not Always.
However, that wouldn't work if those notifications could be retrieved through getDeliveredNotifications, since that would tell you the user had been "there" even when they didn't approve of your app having that "knowledge".
How can I retrieve such notifications after they have been delivered?
I don't think you can. I think you could clear them by calling removeDeliveredNotificationsWithIdentifiers or removeAllDeliveredNotifications, but I don't think there is any way for you know whether or not they were there.
__
Kevin Elliott
DTS Engineer, CoreOS/Hardware