iOS10全新推送功能实现代码

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

#import <UserNotifications/UserNotifications.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 // Override point for customization after application launch.

 /* APP未启动,点击推送消息的情况下 iOS10遗弃UIApplicationLaunchOptionsLocalNotificationKey,使用代理UNUserNotificationCenterDelegate方法didReceiveNotificationResponse:withCompletionHandler:获取本地推送
 */
// NSDictionary *localUserInfo = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
// if (localUserInfo) {
// NSLog(@"localUserInfo:%@",localUserInfo);
// //APP未启动,点击推送消息
// }
 NSDictionary *remoteUserInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
 if (remoteUserInfo) {
 NSLog(@"remoteUserInfo:%@",remoteUserInfo);
 //APP未启动,点击推送消息,iOS10下还是跟以前一样在此获取
 }
 [self registerNotification];
 return YES;
}

注册推送方法的改变:

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

- (void)registerNotification{
 /*
 identifier:行为标识符,用于调用代理方法时识别是哪种行为。
 title:行为名称。
 UIUserNotificationActivationMode:即行为是否打开APP。
 authenticationRequired:是否需要解锁。
 destructive:这个决定按钮显示颜色,YES的话按钮会是红色。
 behavior:点击按钮文字输入,是否弹出键盘
 */
 UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"策略1行为1" options:UNNotificationActionOptionForeground];
 /*iOS9实现方法
 UIMutableUserNotificationAction * action1 = [[UIMutableUserNotificationAction alloc] init];
 action1.identifier = @"action1";
 action1.title=@"策略1行为1";
 action1.activationMode = UIUserNotificationActivationModeForeground;
 action1.destructive = YES;
 */

 UNTextInputNotificationAction *action2 = [UNTextInputNotificationAction actionWithIdentifier:@"action2" title:@"策略1行为2" options:UNNotificationActionOptionDestructive textInputButtonTitle:@"textInputButtonTitle" textInputPlaceholder:@"textInputPlaceholder"];
 /*iOS9实现方法
 UIMutableUserNotificationAction * action2 = [[UIMutableUserNotificationAction alloc] init];
 action2.identifier = @"action2";
 action2.title=@"策略1行为2";
 action2.activationMode = UIUserNotificationActivationModeBackground;
 action2.authenticationRequired = NO;
 action2.destructive = NO;
 action2.behavior = UIUserNotificationActionBehaviorTextInput;//点击按钮文字输入,是否弹出键盘
 */

 UNNotificationCategory *category1 = [UNNotificationCategory categoryWithIdentifier:@"Category1" actions:@[action2,action1] minimalActions:@[action2,action1] intentIdentifiers:@[@"action1",@"action2"] options:UNNotificationCategoryOptionCustomDismissAction];
 // UIMutableUserNotificationCategory * category1 = [[UIMutableUserNotificationCategory alloc] init];
 // category1.identifier = @"Category1";
 // [category1 setActions:@[action2,action1] forContext:(UIUserNotificationActionContextDefault)];

 UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"action3" title:@"策略2行为1" options:UNNotificationActionOptionForeground];
 // UIMutableUserNotificationAction * action3 = [[UIMutableUserNotificationAction alloc] init];
 // action3.identifier = @"action3";
 // action3.title=@"策略2行为1";
 // action3.activationMode = UIUserNotificationActivationModeForeground;
 // action3.destructive = YES;

 UNNotificationAction *action4 = [UNNotificationAction actionWithIdentifier:@"action4" title:@"策略2行为2" options:UNNotificationActionOptionForeground];
 // UIMutableUserNotificationAction * action4 = [[UIMutableUserNotificationAction alloc] init];
 // action4.identifier = @"action4";
 // action4.title=@"策略2行为2";
 // action4.activationMode = UIUserNotificationActivationModeBackground;
 // action4.authenticationRequired = NO;
 // action4.destructive = NO;

 UNNotificationCategory *category2 = [UNNotificationCategory categoryWithIdentifier:@"Category2" actions:@[action3,action4] minimalActions:@[action3,action4] intentIdentifiers:@[@"action3",@"action4"] options:UNNotificationCategoryOptionCustomDismissAction];
 // UIMutableUserNotificationCategory * category2 = [[UIMutableUserNotificationCategory alloc] init];
 // category2.identifier = @"Category2";
 // [category2 setActions:@[action4,action3] forContext:(UIUserNotificationActionContextDefault)];

 [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category1,category2, nil]];
 [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
 NSLog(@"completionHandler");
 }];
 /*iOS9实现方法
 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:[NSSet setWithObjects: category1,category2, nil]];

 [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
 */
 [[UIApplication sharedApplication] registerForRemoteNotifications];

 [UNUserNotificationCenter currentNotificationCenter].delegate = self;
}

代理方法的改变:

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

#pragma mark -

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings NS_AVAILABLE_IOS(8_0) __TVOS_PROHIBITED{
 NSLog(@"didRegisterUserNotificationSettings");
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0){
 NSLog(@"deviceToken:%@",deviceToken);
 NSString *deviceTokenSt = [[[[deviceToken description]
   stringByReplacingOccurrencesOfString:@"<" withString:@""]
  stringByReplacingOccurrencesOfString:@">" withString:@""]
  stringByReplacingOccurrencesOfString:@" " withString:@""];
 NSLog(@"deviceTokenSt:%@",deviceTokenSt);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){
 NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error);
}

/*iOS9使用方法
- (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"){

}
*/

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
 NSLog(@"willPresentNotification:%@",notification.request.content.title);

 // 这里真实需要处理交互的地方
 // 获取通知所带的数据
 NSString *notMess = [notification.request.content.userInfo objectForKey:@"aps"];

}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
 //在没有启动本App时,收到服务器推送消息,下拉消息会有快捷回复的按钮,点击按钮后调用的方法,根据identifier来判断点击的哪个按钮
 NSString *notMess = [response.notification.request.content.userInfo objectForKey:@"aps"];
 NSLog(@"didReceiveNotificationResponse:%@",response.notification.request.content.title);
// response.notification.request.identifier
}

//远程推送APP在前台
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
 NSLog(@"didReceiveRemoteNotification:%@",userInfo);
}

/*
- (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
{

}
*/
/*
// 本地通知回调函数,当应用程序在前台时调用
- (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{
 NSLog(@"didReceiveLocalNotification:%@",notification.userInfo);

 // 这里真实需要处理交互的地方
 // 获取通知所带的数据
 NSString *notMess = [notification.userInfo objectForKey:@"aps"];
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知(前台)"
    message:notMess
    delegate:nil
   cancelButtonTitle:@"OK"
   otherButtonTitles:nil];
 [alert show];

 // 更新显示的徽章个数
 NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
 badge--;
 badge = badge >= 0 ? badge : 0;
 [UIApplication sharedApplication].applicationIconBadgeNumber = badge;

 // 在不需要再推送时,可以取消推送
 [FirstViewController cancelLocalNotificationWithKey:@"key"];

}

- (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
{
 //在非本App界面时收到本地消息,下拉消息会有快捷回复的按钮,点击按钮后调用的方法,根据identifier来判断点击的哪个按钮,notification为消息内容
 NSLog(@"%@----%@",identifier,notification);
 completionHandler();//处理完消息,最后一定要调用这个代码块
}
*/

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

本文已被整理到了《iOS推送教程》,欢迎大家学习阅读。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • iOS10 适配远程推送功能实现代码

    iOS10正式版发布之后,网上各种适配XCode8以及iOS10的文章满天飞.但对于iOS10适配远程推送的文章却不多.iOS10对于推送的修改还是非常大的,新增了UserNotifications Framework,今天就结合自己的项目,说一说实际适配的情况. 一.Capabilities中打开Push Notifications 开关 在XCode7中这里的开关不打卡,推送也是可以正常使用的,但是在XCode8中,这里的开关必须要打开,不然会报错: Error Domain=NSCocoa

  • iOS10推送之基础知识(必看篇)

    前言 在北京时间9月14号凌晨1点,苹果正式推送iOS 10正式版,下面给大家详细的介绍iOS10推送的基础知识,在看完简单入门篇大家就可以简单适配了,然后再通过中级篇的内容,相信对大家学习理解有很大的帮助,下面话不多说了,来看看吧. 一.简单入门篇 相对简单的推送证书以及环境的问题,我就不在这里讲啦,我在这里说的,是指原有工程的适配. 1.首先我们需要打开下面的开关.所有的推送平台,不管是极光还是什么的,要想收到推送,这个是必须打开的哟~ 之后,系统会生成一个我们以前没见过的文件,如图: 可能

  • 解析iOS10中的极光推送消息的适配

    iOS10发布后,发现项目中的极光推送接收消息异常了. 查了相关资料后才发现,iOS10中对于通知做了不少改变.同时也发现极光也很快更新了对应的SDK. 现在就把适配修改的做法分享一下,希望对有需要的童鞋有所帮助. 具体做法如下: 注意:必须先安装Xcode8.0版本. 一.添加相关的SKD,或framework文件 1.添加UserNotification.framework 2.更新jpush的SDK(最新版本:jpush-ios-2.1.9.a)https://www.jiguang.cn

  • 更新了Xcode8 及 iOS10遇到的问题小结

    更新了Xcode8 以及 iOS10,App访问用户的相机.相册.麦克风.通讯录的权限都需要重新进行相关的配置,不然在Xcode8中打开编译的话会直接crash. 需要在info.plist中添加App需要的一些设备权限. 相机NSCameraUsageDescription 相册NSPhotoLibraryUsageDescription 通讯录NSContactsUsageDescription 始终访问位置NSLocationAlwaysUsageDescription 位置NSLocat

  • iOS10适配之权限Crash问题的完美解决方案

    升级 iOS 10 之后目测坑还是挺多的,记录一下吧,看看到时候会不会成为一个系列. 直入正题吧 今天在写 Swift 3 相关的一个项目小小练下手,发现调用相机,崩了.试试看调用相册,又特么崩了.然后看到控制台输出了以下信息: This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must cont

  • IOS10 解决权限崩溃问题详解

    今天 手机升级了 iOS10 Beta,然后用正在开发的项目 装了个ipa包,发现点击有关 权限访问 直接Crash了,并在控制台输出了一些信息: This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSContactsUsageDescription key wit

  • Xcode8以及iOS10适配等常见问题汇总(整理篇)

    随着iOS 10的更新以及Xcdoe 8的更新出现了很多问题,今天小编抽时间把我遇到的坑和大家分享下,一起看看吧. 1.访问权权限问题 iOS 10 开始对访问用户隐私权限更加严格,如果你不设置就会直接崩溃,解决办法都是在info.plist文件添加对应的Key-Value就可以了. PS:对应的value可以自定义填写 2.Xcode 8 运行打印一堆Log的解决办法 只要在Run->Arguments->Environment Variables 添加如下key-value值即可 OS_A

  • Xcode8、iOS10升级问题记录

    1.webView的代理方法: 升级前: - (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error 升级后: - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 要删除NSError前面的 nullable,否则报错. 2.关于触屏事件的一些操作: 升级前: - (void)touchesC

  • 110.iOS10新特性适配教程XCode8新特性解析

    iOS10 新特性 SiriKit SiriKit的功能非常强大,支持音频.视频.消息发送接收.搜索照片.预订行程.管理锻炼等等.在用到此服务时,siri会发送Intent对象,里面包括用户的请求和各种数据,可以对这个intent处理选择适当的响应. 这个功能主要是看这两个头文件(#import Proactive Suggestions 系统预先建议 背景就是iOS9的时候系统给予的主动建议会通过:Spolight搜索,Safari搜索,Handoff,或者siri建议. 在iOS10之后新增

  • iOS10开发和Xcode 8新特性及常见问题解析

    iOS 10 开发这次更新主要表现在以下这几个方面. 1.语音识别 苹果官方在文档中新增了API Speech,那么在以前我们处理语音识别非常的繁琐甚至很多时候可能需要借助于第三方框架处理,那么苹果推出了这个后,我们以后处理起来就非常的方便了,speech具有以下特点: 可以实现连续的语音识别 可以对语 音文件或者语音流进行识别 最佳化自由格式的听写(可理解为多语言支持)和搜索式的字符串 核心代码: #import <Speech/Speech.h> /** 语音识别同样的需要真机进行测试 ,

  • iOS10 推送最新特性研究

    最近在研究iOS10关于推送的新特性, 相比之前确实做了很大的改变,总结起来主要是以下几点: 1.推送内容更加丰富,由之前的alert 到现在的title, subtitle, body  2.推送统一由trigger触发  3.可以为推送增加附件,如图片.音频.视频,这就使推送内容更加丰富多彩  4.可以方便的更新推送内容 import 新框架 添加新的框架 UserNotifications.framework #import <UserNotifications/UserNotificat

  • IOS10 远程推送适配详细介绍

    IOS10 远程推送适配 iOS10推送新增了UserNotifications Framework,使用起来其实很简单. 建议看看极光推送的Demo,里面写的更详细. 只是在iOS10以上系统上点击通知栏,回调方法不再走原来的这两个方法 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {} - (void)application:(UIA

随机推荐