使用 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 中。