随着 iOS 8 的推出,一个令人兴奋的新 API 用于创建交互式通知。这些允许您在您的应用程序之外为您的用户提供额外的功能。
让我们开始吧。 iOS 8 中需要 3 个新类:UIUserNotificationSettings, UIUserNotificationCategory, UIUserNotificationAction 及其可变对应物。
您现在可以注册自定义通知类别和操作,而不是简单地注册通知类型(声音、横幅、警报)。类别描述了您的应用程序发送的自定义类型的通知,并包含用户可以执行的响应操作。例如,您收到通知,有人在社交网络上关注您。作为回应,您可能想要关注或忽略它们。
NSString * const NotificationCategoryIdent = @"ACTIONABLE";
NSString * const NotificationActionOneIdent = @"ACTION_ONE";
NSString * const NotificationActionTwoIdent = @"ACTION_TWO";
- (void)registerForNotification {
UIMutableUserNotificationAction *action1;
action1 = [[UIMutableUserNotificationAction alloc] init];
[action1 setActivationMode:UIUserNotificationActivationModeBackground];
[action1 setTitle:@"Action 1"];
[action1 setIdentifier:NotificationActionOneIdent];
[action1 setDestructive:NO];
[action1 setAuthenticationRequired:NO];
UIMutableUserNotificationAction *action2;
action2 = [[UIMutableUserNotificationAction alloc] init];
[action2 setActivationMode:UIUserNotificationActivationModeBackground];
[action2 setTitle:@"Action 2"];
[action2 setIdentifier:NotificationActionTwoIdent];
[action2 setDestructive:NO];
[action2 setAuthenticationRequired:NO];
UIMutableUserNotificationCategory *actionCategory;
actionCategory = [[UIMutableUserNotificationCategory alloc] init];
[actionCategory setIdentifier:NotificationCategoryIdent];
[actionCategory setActions:@[action1, action2]
forContext:UIUserNotificationActionContextDefault];
NSSet *categories = [NSSet setWithObject:actionCategory];
UIUserNotificationType types = (UIUserNotificationTypeAlert|
UIUserNotificationTypeSound|
UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings;
settings = [UIUserNotificationSettings settingsForTypes:types
categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
//JSON 负载:
{
"aps" : {
"alert" : "Pull down to interact.",
"category" : "ACTIONABLE"
}
}
现在要处理用户选择的操作,UIApplicationDelegate 协议上有 2 个新方法:\
application:handleActionWithIdentifier:forLocalNotification:completionHandler:
application:handleActionWithIdentifier:forRemoteNotification:completionHandler:
当用户从您的推送通知中选择一个操作时,这些方法将在后台被调用。
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
if ([identifier isEqualToString:NotificationActionOneIdent]) {
NSLog(@"You chose action 1.");
}
else if ([identifier isEqualToString:NotificationActionTwoIdent]) {
NSLog(@"You chose action 2.");
}
if (completionHandler) {
completionHandler();
}
}