iOS Managing local notifications using UUID


Example

Often times you will need to be able to manage your notifications, by being able to keep track of them and cancel 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)

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.sharedApplication().cancelLocalNotification(notification)
}

Objective-C

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

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

You would probably want to store all of these UUID's in Core Data or Realm.