iOS 8中創建交互式通知
iOS 8提供了一個令人興奮的新API來創建交互式通知(interactive notifications),它能讓你在你的應用之外為用戶提供額外的功能。我發現網上還沒有關于如何實現它的比較好的示例教程,所以我將在這篇文章里來實現一個簡單的交互式通知示例,分享給大家。

為了創建交互式通知,需要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協議添加兩個新方法:
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(); }} 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!