为了创建交互式通知,需要iOS 8提供的3个新类:UIUserNotificationSettings, UIUserNotificationCategory, UIUserNotificationAction 以及它们的变体。
和以前简单地注册通知类型(sounds、banners、alerts)相比,现在你可以注册自定义的通知类别(categories)和动作(actions)。类别描述了应用自定义的通知类型,并且包含用户能够执行的响应动作。比如,你收到一个通知说某人在社交网上了关注了你,作为回应你可能会想要关注他或者忽略。
这里是一个非常简单的使用Objective-C编写的示例,演示如何注册一个包含两个动作的通知。
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];
}
要发送这个通知类型,只需简单的将category添加到声明里。
“aps” : {
“alert” : “Pull down to interact.”,
“category” : “ACTIONABLE”
}
现在为了响应用户选择的操作,你需要在UIApplicationDelegate协议添加两个新方法:
1
2
application:handleActionWithIdentifier:forLocalNotification:completionHandler:
application:handleActionWithIdentifier:forRemoteNotification:completionHandler:
用户从你的推送通知中选择一个动作后,该方法将会在后台被调用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(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();
}
}
如文档所述,通过标示符来判定是哪个动作被选中,最后调用completionHandler,即可大功告成。这里仅仅简单的演示了一下iOS 8 新通知API表面上的功能,今后我将更深入的研究一下,有机会再和大家分享。
文章链接:http://www.cocoachina.com/ios/20141009/9857.html