iOS 远程推送

iOS远程推送主要流程为:注册推送的token,把token上传到服务器->接收到服务器的推送->处理推送。
注册token时,需要用户同意授权进行推送,否则不能获取token,则推送功能无法实现。
远程推送的框架在iOS10之后有更新,因此如果要兼容iOS10之前的系统,则需要进行判断系统版本。

1、注册推送的token并上传

首先打开项目的推送功能,如下图:


图片.png

然后实现注册token的方法,代码如下:

//iOS10之后需要引入新框架
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

- (void)replyPushNotificationAuthorization:(UIApplication *)application{
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        //iOS 10 later
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //必须写代理,不然无法监听通知的接收与点击事件
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error && granted) {
                //用户点击允许
                NSLog(@"PushNotification====注册成功");
            }else{
                //用户点击不允许
                NSLog(@"PushNotification====注册失败");
            }
        }];
        
        //获取通知注册状态
        //        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        //            NSLog(@"PushNotification====%@",settings);
        //        }];
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >8.0){
        //iOS 8 - iOS 9系统
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    //注册远端消息通知获取device token
    [application registerForRemoteNotifications];
}

我们然后在AppDelegate里面实现两个代理方法,在第一次申请token时,需要取得用户的同意,会弹出推送权限申请对话框,当用户同意后会调用token申请成功的代理方法,当用户拒绝后会调用token申请失败的方法。代码如下:

#pragma mark - 授权申请token回调
//token获取成功
- (void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSData  *apnsToken = [NSData dataWithData:deviceToken];
    
    NSString *tokenString = [self getHexStringForData:apnsToken];
    NSLog(@"My token = %@", tokenString);
    
}

- (NSString *)getHexStringForData:(NSData *)data {
    NSUInteger length = [data length];
    char *chars = (char *)[data bytes];
    NSMutableString *hexString = [[NSMutableString alloc] init];
    for (NSUInteger i = 0; i < length; i++) {
        [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", chars[i]]];
    }
    return hexString;
}
//token获取失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

当我们token获取成功后,把token上传到服务器,服务器即可根据token及相关参数可以进行推送。上传根据自己的后台服务器接口进行上传即可。

2、接收到推送及处理

接收到推送时的情况有几种,如下:
APP在没有启动及在后台的情况下收到推送,此时会在通知栏进行显示;
APP在前台收到推送,此时会调用收到推送的方法,是否显示由代码决定。
当用户点击推送时,我们也需要进行处理,此时调用的代理方法也有区别,处理推送的流程如下图(对应推送的处理,我们也需要区分iOS10及iOS10之前的系统):


图片.png

我们在AppDelegate实现相关代理方法,即可处理相应的推送,代码如下:

#pragma mark - function 1
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self replyPushNotificationAuthorization:application];
    NSLog(@"launchOptions == %@",launchOptions);
    return YES;
}

#pragma mark - function 2 iOS 10之前以前的用户
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"push notification did receive remote notification:%@", userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - function 3 iOS10及以后的用户
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"push notification did receive remote notification:%@",notification.request.content.userInfo);
    // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置,决定是否再显示此通知来提醒用户
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}

#pragma mark - function 4 iOS10及以后的用户
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    NSLog(@"push notification did receive remote notification:%@",response.notification.request.content.userInfo);
  completionHandler();
}

对于接收到的推送处理完毕后,一个推送就形成了闭合,完成了它的使命。
Demo地址:https://github.com/XMSECODE/ESCPushNotificationDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 引言:iOS开发,推送可以说是必须的,但是之前对于推送总是概念模糊,最近借公司项目需求,深入了解了一下。“对于知识...
    ibabyblue阅读 1,387评论 36 8
  • 转载请联系作者获取授权,并标明文章作者,谢谢! 大家好,之前的文章讲过了APNs推送的原理。推送开发证书和发布证书...
    OliviaZqy阅读 2,231评论 0 8
  • 基本原理 iOS推送分为Local Notifications(本地推送) 和 Remote Notificati...
    小小球员阅读 1,882评论 1 1
  • 概念相关 1.什么是远程推送通知? 顾名思义,就是从远程服务器推送给客户端的通知(需要联网) 远程推送服务,又称为...
    我是滕先生阅读 3,773评论 9 44
  • Notification 历史和现状 前言 苹果在 iOS 10 中添加了新的框架:UserNotificatio...
    灵度Ling阅读 9,212评论 4 24