博客> iOS10 远程推送的适配
iOS10 远程推送的适配
2017-10-19 21:51 评论:0 阅读:302 tianya2416
远程推送 iOS10适配

1、前言

关于通知,无论远程Push还是本地通知,以往的iOS api暴漏给开发者的接口都是十分有限的,开发者只能对标题和内容进行简单的定义,至于UI展示和用户交互行为相关的部分,开发者开发起来都十分困难。至于本地通知,iOS10之前采用的是UILocationNotification类,远程通知由苹果服务器进行转发,本地通知和远程通知其回调的处理都是通过AppDelegate中的几个回调方法来完成。iOS10系统中,通知功能的增强是一大优化之处,iOS10中将通知功能整合成了一个框架UserNotification,其结构十分类似于iOS8中的UIWebView向WebKit框架整合的思路。今天就来说说前段时间适配踩过的坑。

2、iOS8以前适配

UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
// 注册远程通知 -根据远程通知类型
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];

3、iOS8到iOS10的适配

// 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音) UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound; // 定义用户通知设置 UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:types categories:nil]; // 注册用户通知 - 根据用户通知设置 [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

记得实现代理方法否则会出现无法获取token的现象
#pragma mark -UIApplicationDelegate 用户通知(推送)回调 _IOS 8.0以上使用
/** 已登记用户通知 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    // 注册远程通知(推送)
    [application registerForRemoteNotifications];
}

4、iOS10的适配

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"succeeded!");
            }
        }];
        //如果不设置会造成token 获取失败
        [[UIApplication sharedApplication] registerForRemoteNotifications];

iOS 10的时候引入了#import <UserNotifications>框架不过对于我们适配来说工作量也还好。实现远程推送的两个代理方法
#pragma mark - UNUserNotificationCenterDelegate

//在前台的时候回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    NSDictionary * userInfo  = notification.request.content.userInfo;
    [MGPushOperate pushNow:userInfo IsActive:YES];
}

//从后台进入的时候回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    NSDictionary * userInfo  = response.notification.request.content.userInfo;
    NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n",userInfo);
    [MGPushOperate pushNow:userInfo IsActive:NO];
}

5、介绍一个神器

SmartPush Enter your link description here:

收藏
0
sina weixin mail 回到顶部