iOS10全新推送功能的实现

摘要:
UIUserNotificationActivationMode:操作是否打开APP。AuthenticationRequired:是否解锁。破坏性:这决定了按钮的显示颜色。如果是,按钮将为红色。

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

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

iOS10全新推送功能的实现第1张

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

iOS10全新推送功能的实现第2张

#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]  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]  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插件开发

iOS10全新推送功能的实现第3张

iOS10全新推送功能的实现第4张

免责声明:文章转载自《iOS10全新推送功能的实现》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇分布式系统详解(二)--基础知识(概论)jq 的onchange事件下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

Vue中进行断点调试的两种方式(使用外部浏览器和VsCode Debug for Chrome 插件)

但是在Vue中如果想要进行调试时,如果是在js中调试的话,可以直接添加一个debugger,然后在浏览器中打开检查进行断点调试。比如:在Vue页面中,点击搜索按钮时搜索会触发handleQuery方法resetQuery(){this.resetForm;this.handleQuery();},其中调用了请求查询数据的方法handleQuery(){thi...

Git安装配置(完整版)

/usr/bin/bashcd/var/www/aunsetGIT_DIRgitpulloriginmaster为您提供了另一个权限:chmod755/var/gitdata/a。git/books/post-receivechowngit:git/var/gitdata/a在git/hooks/post-receive模式下,客户端提交代码,服务器项目可以...

Jmeter中获取返回结果中的值

在jmeter的测试中,通常需要在下一个请求中使用上一个请求的返回值。如何获得返回值非常重要。插件下载地址为:http://jmeter-plugins.org/wiki/JSONPathExtractor/下载后,将lib文件夹放在jmeter目录中。...

MIPS学习笔记(一)

本章涉及MIPS变量声明、数据输入和输出、地址获取、分支跳转语句,基本上对应于任何高级语言的最基本操作。该信息的确切形式因汇编程序而异。在MIPS程序集中,标签是后跟冒号的符号名称。)syscall程序的结尾与C类似,可以调用exit函数来停止程序的执行。停止MIPS程序的一种方法是使用类似于在C中调用exit的方法。MIPS中有一个移动指令,它将一个寄存器...

Uni-app v-on监听事件

使用标记上的v-on监视事件。缩写为@click common click events方法:方法:{Focus(){console.log;},blur(){console.log;},confirm(){console.log;},click(){console.log;},tap(){console.log;},longpress(){console....

libffi

Thisislibffi.info,由libffi.texi生产的bymakeinfo版本5.1。本手册适用于libffi,一个可移植的外国函数接口库。版权所有(C)200820102011redhat,股份有限公司。许可授予复制、分发...