使用 UUID 管理本地通知

通常,你需要能够管理通知,能够跟踪并取消通知。

跟踪通知

你可以为通知分配 UUID(通用唯一标识符),以便跟踪它:

迅速

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];

取消通知

要取消通知,我们首先会获得所有通知的列表,然后找到具有匹配 UUID 的通知。最后,我们取消它。

迅速

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;
    }
}

你可能希望将所有这些 UUID 存储在 Core Data 或 Realm 中。