iOS10全新推送功能的实现

从iOS8.0开始推送功能的实现在不断改变,功能也在不断增加,iOS10又出来了一个推送插件的开发(见最后图),废话不多说直接上代码:

在开始之前需要打开一个推送开关,不然无法获取deviceToken,老项目或者出现deviceToken无效的情况:如图:



打开后会生成entitlements文件,需要有APS Environment


或许还应该打开这个


#import <UserNotifications/UserNotifications.h>


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  2.     // Override point for customization after application launch.  
  3.       
  4.     /* APP未启动,点击推送消息的情况下 iOS10遗弃UIApplicationLaunchOptionsLocalNotificationKey,使用代理UNUserNotificationCenterDelegate方法didReceiveNotificationResponse:withCompletionHandler:获取本地推送 
  5.      */  
  6. //    NSDictionary *localUserInfo = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];  
  7. //    if (localUserInfo) {  
  8. //        NSLog(@"localUserInfo:%@",localUserInfo);  
  9. //        //APP未启动,点击推送消息  
  10. //    }  
  11.     NSDictionary *remoteUserInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];  
  12.     if (remoteUserInfo) {  
  13.         NSLog(@"remoteUserInfo:%@",remoteUserInfo);  
  14.         //APP未启动,点击推送消息,iOS10下还是跟以前一样在此获取  
  15.     }  
  16.     [self registerNotification];  
  17.     return YES;  
  18. }  

注册推送方法的改变:

新增库 #import <UserNotifications/UserNotifications.h>  推送单列UNUserNotificationCenter 等API


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)registerNotification{  
  2.     /* 
  3.      identifier:行为标识符,用于调用代理方法时识别是哪种行为。 
  4.      title:行为名称。 
  5.      UIUserNotificationActivationMode:即行为是否打开APP。 
  6.      authenticationRequired:是否需要解锁。 
  7.      destructive:这个决定按钮显示颜色,YES的话按钮会是红色。 
  8.      behavior:点击按钮文字输入,是否弹出键盘 
  9.      */  
  10.     UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"策略1行为1" options:UNNotificationActionOptionForeground];  
  11.     /*iOS9实现方法 
  12.     UIMutableUserNotificationAction * action1 = [[UIMutableUserNotificationAction alloc] init]; 
  13.     action1.identifier = @"action1"; 
  14.     action1.title=@"策略1行为1"; 
  15.     action1.activationMode = UIUserNotificationActivationModeForeground; 
  16.     action1.destructive = YES; 
  17.      */  
  18.       
  19.     UNTextInputNotificationAction *action2 = [UNTextInputNotificationAction actionWithIdentifier:@"action2" title:@"策略1行为2" options:UNNotificationActionOptionDestructive textInputButtonTitle:@"textInputButtonTitle" textInputPlaceholder:@"textInputPlaceholder"];  
  20.     /*iOS9实现方法 
  21.         UIMutableUserNotificationAction * action2 = [[UIMutableUserNotificationAction alloc] init]; 
  22.         action2.identifier = @"action2"; 
  23.         action2.title=@"策略1行为2"; 
  24.         action2.activationMode = UIUserNotificationActivationModeBackground; 
  25.         action2.authenticationRequired = NO; 
  26.         action2.destructive = NO; 
  27.         action2.behavior = UIUserNotificationActionBehaviorTextInput;//点击按钮文字输入,是否弹出键盘 
  28.     */  
  29.       
  30.     UNNotificationCategory *category1 = [UNNotificationCategory categoryWithIdentifier:@"Category1" actions:@[action2,action1 intentIdentifiers:@[@"action1",@"action2"] options:UNNotificationCategoryOptionCustomDismissAction];  
  31.     //        UIMutableUserNotificationCategory * category1 = [[UIMutableUserNotificationCategory alloc] init];  
  32.     //        category1.identifier = @"Category1";  
  33.     //        [category1 setActions:@[action2,action1] forContext:(UIUserNotificationActionContextDefault)];  
  34.       
  35.     UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"action3" title:@"策略2行为1" options:UNNotificationActionOptionForeground];  
  36.     //        UIMutableUserNotificationAction * action3 = [[UIMutableUserNotificationAction alloc] init];  
  37.     //        action3.identifier = @"action3";  
  38.     //        action3.title=@"策略2行为1";  
  39.     //        action3.activationMode = UIUserNotificationActivationModeForeground;  
  40.     //        action3.destructive = YES;  
  41.       
  42.     UNNotificationAction *action4 = [UNNotificationAction actionWithIdentifier:@"action4" title:@"策略2行为2" options:UNNotificationActionOptionForeground];  
  43.     //        UIMutableUserNotificationAction * action4 = [[UIMutableUserNotificationAction alloc] init];  
  44.     //        action4.identifier = @"action4";  
  45.     //        action4.title=@"策略2行为2";  
  46.     //        action4.activationMode = UIUserNotificationActivationModeBackground;  
  47.     //        action4.authenticationRequired = NO;  
  48.     //        action4.destructive = NO;  
  49.       
  50.     UNNotificationCategory *category2 = [UNNotificationCategory categoryWithIdentifier:@"Category2" actions:@[action3,action4 intentIdentifiers:@[@"action3",@"action4"] options:UNNotificationCategoryOptionCustomDismissAction];  
  51.     //        UIMutableUserNotificationCategory * category2 = [[UIMutableUserNotificationCategory alloc] init];  
  52.     //        category2.identifier = @"Category2";  
  53.     //        [category2 setActions:@[action4,action3] forContext:(UIUserNotificationActionContextDefault)];  
  54.       
  55.       
  56.     [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category1,category2, nil nil]];  
  57.     [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {  
  58.         NSLog(@"completionHandler");  
  59.     }];  
  60.     /*iOS9实现方法 
  61.     UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:[NSSet setWithObjects: category1,category2, nil]]; 
  62.  
  63.     [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; 
  64.     */  
  65.     [[UIApplication sharedApplication] registerForRemoteNotifications];  
  66.       
  67.       
  68.     [UNUserNotificationCenter currentNotificationCenter].delegate = self;  
  69. }  



代理方法的改变:

一些本地和远程推送的回调放在了同一个代理方法

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #pragma mark -  
  2.   
  3. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings NS_AVAILABLE_IOS(8_0) __TVOS_PROHIBITED{  
  4.     NSLog(@"didRegisterUserNotificationSettings");  
  5. }  
  6.   
  7. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0){  
  8.     NSLog(@"deviceToken:%@",deviceToken);  
  9.     NSString *deviceTokenSt = [[[[deviceToken description]  
  10.                                  stringByReplacingOccurrencesOfString:@"<" withString:@""]  
  11.                                 stringByReplacingOccurrencesOfString:@">" withString:@""]  
  12.                                stringByReplacingOccurrencesOfString:@" " withString:@""];  
  13.     NSLog(@"deviceTokenSt:%@",deviceTokenSt);  
  14. }  
  15.   
  16. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){  
  17.     NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error);  
  18. }  
  19.   
  20. /*iOS9使用方法 
  21. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo NS_DEPRECATED_IOS(3_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] for user visible notifications and -[UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] for silent remote notifications"){ 
  22.      
  23. } 
  24. */  
  25.   
  26. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{  
  27.     NSLog(@"willPresentNotification:%@",notification.request.content.title);  
  28.       
  29.     // 这里真实需要处理交互的地方  
  30.     // 获取通知所带的数据  
  31.     NSString *notMess = [notification.request.content.userInfo objectForKey:@"aps"];  
  32.       
  33. }  
  34.   
  35. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{  
  36.     //在没有启动本App时,收到服务器推送消息,下拉消息会有快捷回复的按钮,点击按钮后调用的方法,根据identifier来判断点击的哪个按钮  
  37.     NSString *notMess = [response.notification.request.content.userInfo objectForKey:@"aps"];  
  38.     NSLog(@"didReceiveNotificationResponse:%@",response.notification.request.content.title);  
  39. //    response.notification.request.identifier  
  40. }  
  41.   
  42. //远程推送APP在前台  
  43. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{  
  44.     NSLog(@"didReceiveRemoteNotification:%@",userInfo);  
  45. }  
  46.   
  47. /* 
  48. - (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler NS_DEPRECATED_IOS(8_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]") __TVOS_PROHIBITED 
  49. { 
  50.      
  51. } 
  52. */  
  53. /* 
  54. // 本地通知回调函数,当应用程序在前台时调用 
  55. - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification NS_DEPRECATED_IOS(4_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]") __TVOS_PROHIBITED{ 
  56.     NSLog(@"didReceiveLocalNotification:%@",notification.userInfo); 
  57.      
  58.      
  59.     // 这里真实需要处理交互的地方 
  60.     // 获取通知所带的数据 
  61.     NSString *notMess = [notification.userInfo objectForKey:@"aps"]; 
  62.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知(前台)" 
  63.                                                     message:notMess 
  64.                                                    delegate:nil 
  65.                                           cancelButtonTitle:@"OK" 
  66.                                           otherButtonTitles:nil]; 
  67.     [alert show]; 
  68.      
  69.     // 更新显示的徽章个数 
  70.     NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber; 
  71.     badge--; 
  72.     badge = badge >= 0 ? badge : 0; 
  73.     [UIApplication sharedApplication].applicationIconBadgeNumber = badge; 
  74.      
  75.     // 在不需要再推送时,可以取消推送 
  76.     [FirstViewController cancelLocalNotificationWithKey:@"key"]; 
  77.  
  78. } 
  79.  
  80.  
  81. - (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler NS_DEPRECATED_IOS(8_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]") __TVOS_PROHIBITED 
  82. { 
  83.     //在非本App界面时收到本地消息,下拉消息会有快捷回复的按钮,点击按钮后调用的方法,根据identifier来判断点击的哪个按钮,notification为消息内容 
  84.     NSLog(@"%@----%@",identifier,notification); 
  85.     completionHandler();//处理完消息,最后一定要调用这个代码块 
  86. } 
  87. */  

还有推送插件开发: 类似iOS tody widget插件开发

   

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 这里我们要注意一定要有"mutable-content""1",以及一定要有Alert的字段,否则可能会拦截通知失败。(苹果文档说的)。除此之外,我们还可以添加自定义字段,比如,图片地址,图片类型  
  2. {  
  3.     "aps": {  
  4.         "alert""message.",  
  5.         "badge"1,  
  6.         "sound""default",  
  7.         "mutable-content""1",  
  8.         "imageAbsoluteString""http://xxxx"  
  9.   
  10.     }  
  11. }  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值