iOS 8提供的3個新類:UIUserNotificationSettings,UIUserNotificationCategory,UIUserNotificationAction以及它們的變體看尼。
和 以前簡單地注冊通知類型(sounds恢口、banners陡蝇、alerts)相比领炫,現(xiàn)在你可以注冊自定義的通知類別(categories)和動作 (actions)涂圆。類別描述了應(yīng)用自定義的通知類型宵统,并且包含用戶能夠執(zhí)行的響應(yīng)動作蜒犯。比如絮供,你收到一個通知說某人在社交網(wǎng)上了關(guān)注了你子巾,作為回應(yīng)你可 能會想要關(guān)注他或者忽略帆赢。
#define NotificationCategoryIdent? @"ACTIONABLE"
#define NotificationActionOneIdent? @"ACTION_ONE"
#define NotificationActionTwoIdent? @"ACTION_TWO"
注冊通知
UIMutableUserNotificationAction*action1;
action1=[[UIMutableUserNotificationActionalloc]init];
[action1setActivationMode:UIUserNotificationActivationModeBackground];
[action1setTitle:@"Action1"];
[action1setIdentifier:NotificationActionOneIdent];
[action1setDestructive:NO];
[action1setAuthenticationRequired:NO];
UIMutableUserNotificationAction*action2;
action2=[[UIMutableUserNotificationActionalloc]init];
[action2setActivationMode:UIUserNotificationActivationModeBackground];
[action2setTitle:@"Action2"];
[action2setIdentifier:NotificationActionTwoIdent];
[action2setDestructive:NO];
[action2setAuthenticationRequired:NO];
UIMutableUserNotificationCategory*actionCategory;
actionCategory=[[UIMutableUserNotificationCategoryalloc]init];
[actionCategorysetIdentifier:NotificationCategoryIdent];
[actionCategorysetActions:@[action1,action2]
forContext:UIUserNotificationActionContextDefault];
NSSet*categories=[NSSetsetWithObject:actionCategory];
UIUserNotificationTypetypes=(UIUserNotificationTypeAlert|
UIUserNotificationTypeSound|
UIUserNotificationTypeBadge);
UIUserNotificationSettings*settings;
settings=[UIUserNotificationSettingssettingsForTypes:types
categories:categories];
[[UIApplicationsharedApplication]registerUserNotificationSettings:settings];
}
要發(fā)送這個通知類型,只需簡單的將category添加到聲明里线梗。
{"aps":{"alert":"測試","category":"ACTIONABLE","badge":1,"sound":"default","custom":{"t":"jump","p":"second"}}}
現(xiàn)在為了響應(yīng)用戶選擇的操作椰于,你需要在UIApplicationDelegate協(xié)議添加兩個新方法:
application:handleActionWithIdentifier:forLocalNotification:completionHandler:
application:handleActionWithIdentifier:forRemoteNotification:completionHandler:
用戶從你的推送通知中選擇一個動作后,該方法將會在后臺被調(diào)用仪搔。
-(void)application:(UIApplication*)applicationhandleActionWithIdentifier:(NSString*)identifierforRemoteNotification:(NSDictionary*)userInfocompletionHandler:(void(^)())completionHandler{
if([identifierisEqualToString:NotificationActionOneIdent]){
NSLog(@"Youchoseaction1.");
}
elseif([identifierisEqualToString:NotificationActionTwoIdent]){
NSLog(@"Youchoseaction2.");
}
if(completionHandler){
completionHandler();
}
}