Managing local notifications using UUID

suggest change

Often you need to track notifications so you can cancel one of them.

Track a notification

You can assign a UUID (universally unique identifier) to a notification, so you can track it:

Swift

let notification = UILocalNotification()
let uuid = NSUUID().uuidString
notification.userInfo = ["UUID": uuid]
UIApplication.shared.scheduleLocalNotification(notification)

The notification above has no fireDate or alertBody. Scheduling it does not show an alert; the sample only stores the UUID. UILocalNotification is the pre-iOS 10 API.

Objective-C

UILocalNotification *notification = [[UILocalNotification alloc] init];
NSString *uuid = [[NSUUID UUID] UUIDString];
notification.userInfo = @{ @"UUID": uuid };
[[UIApplication sharedApplication] scheduleLocalNotification:notification];

Cancel a notification

To cancel a notification, we first get a list of all the notifications and then find the one with a matching UUID. Finally, we cancel it.

Swift

let scheduledNotifications = UIApplication.shared.scheduledLocalNotifications

guard let scheduledNotifications = scheduledNotifications else {
    return
}

for notification in scheduledNotifications where "\(notification.userInfo!["UUID"]!)" == UUID_TO_CANCEL {
    UIApplication.shared.cancelLocalNotification(notification)
}

Objective-C

NSArray *scheduledNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];

for (UILocalNotification *notification in scheduledNotifications) {
    if ([[notification.userInfo objectForKey:@"UUID"] isEqualToString:UUID_TO_CANCEL]) {
        [[UIApplication sharedApplication] cancelLocalNotification:notification];
        break;
    }
}

UUID_TO_CANCEL must be the same string stored in userInfo. The Swift loop force-unwraps userInfo and "UUID", so a notification without that entry crashes. You would probably want to store all of these UUIDs in Core Data or Realm.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents