iOS 10推送使用总结

概述
现在市面上大多数app,都有根据某种条件,服务端主动向用户推送消息的需求。面对这个需求,首先想到的是长链接,如果服务端集成了HTTP/2的话,还可以用Server Push。安卓在处理类似业务时就是这么干的,美其名曰透传消息。但是我们期望的是,无论是app退后台还是被结束进程,都可以正常收到消息。这就需要用到系统集的推送。而在iOS平台或者说苹果全系统平台,就是伟大的Apple Push Notification service 简称APNs。

开启app的推送通知能力

在工程的Capability标签下,打开 Push Notifications 开关

avatar

然后它会在你的AppId下增加下图的配置,你需要根据要求配置相关的推送证书(这块就不说了)

image

以上就是配置推送环境的步骤,下面就可以写代码了

获取推送权限

代码如下,最好在 AppDelegatedidFinishLaunchingWithOptions 这个方法里面且做

if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
         center.delegate = self; // 注意这里 不设置代理不会走推送的两个代理方法
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"iOS 10后 - 用户授权通知权限");
            }else {
                NSLog(@"iOS 10后 - 用户拒绝通知权限");
            }
        }];
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"%@", settings);
        }];
    }else {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }

注册完成之后我们还需要执行[[UIApplication sharedApplication] registerForRemoteNotifications];获取推送的DeviceToken
系统就会去获取,然后在didRegisterForRemoteNotificationsWithDeviceToken 这个代理方法中返回

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    if (@available(iOS 13.0, *)) {
        NSMutableString *deviceTokenString = [NSMutableString string];
        const char *bytes = deviceToken.bytes;
        NSInteger count = deviceToken.length;
        for (int i = 0; i < count; i++) {
            [deviceTokenString appendFormat:@"%02x", bytes[i]&0x000000FF];
        }
        NSLog(@"iOS13 deviceToken:%@", deviceTokenString);
    } else {
        NSString *deviceTokenStr =  [[[[deviceToken description]
                                       stringByReplacingOccurrencesOfString:@"<" withString:@""]
                                      stringByReplacingOccurrencesOfString:@">" withString:@""]
                                     stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSLog(@"iOS13-Pre deviceToken:%@", deviceTokenStr);
    }
    
}

获取到token后给服务器,执行推送指令。
服务器推送格式:
注意:body和title必须要有一个才行,不然推送不弹窗。

 {
   "aps" : {
     "alert" : {
       "title" : "Test-Push",
       "body" : "Your message Here"
     },
   }
 }

这个时候我们还不能收到推送,因为我们还没实现 UNUserNotificationCenter的代理方法
代码如下

/// 收到推送后,会先调用这个方法,它可以设置推送要显示的方式是啥 常用的配置如代码所示
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    NSLog(@"willPresentNotification");
    UNNotificationPresentationOptions options = UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge;
    completionHandler(options);
}
// 上面的代理方法走了之后,会在用户与你推送的通知进行交互时被调用,包括用户通过通知打开了你的应用,或者点击或者触发了某个 action
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
{
    UNNotificationContent *content = response.notification.request.content;
    //NSLog(@"didReceiveNotificationResponse %@", content);
    NSDictionary *responseDict = content.userInfo;
    NSLog(@"didReceiveNotificationResponse %@", responseDict);
    completionHandler();
}

静默推送

就是实现下面的代理方法

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

这里有个注意点:如果你实现了这个方法且运行在iOS10以下的设备的时候,所有的远程推送都是走这个方法的,iOS10之前的didReceiveRemoteNotification这个代理方法是不会走的。除非你没实现上面的代理方法

当我们不请求推送权限,或者用户拒绝或者主动关闭了推送权限,推送还是可以正常到达设备的。但是没有横幅也没有声音,是以静默形式呈现。如果跟常规的推送混合着使用,场景会复杂一些。
必须打开后台模式,并勾选Remote notification,我们之前介绍的那些方法才会被触发。
我们在payload中不包含alert、sound、badge,无论app推送权限是否打开,都属于静默推送。
原则上,后台模式的推送应该是静默推送。在iOS13以后,需要在请求头中apns-push-type字段设置为backgroud。而如果不是真正的静默推送,有被APNs丢弃的危险。

在服务推送的时候需要在payload中包含content-available并且值为1 这样才会走上面的代理方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
这里补充下iOS10以下的设备如果实现了上面的代理方法,所有推送都会走那里不会走原来的- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo方法

远程推送格式为:(大小限制好像是5kb

 {
   "aps" : {
     "alert" : {
       "title" : "Test-Push",
       "body" : "Your message Here"
     },
     "content-available" : 1
   }
 }
image

静默推送和UNUserNotificationCenter同时使用的情况下

注意:
fetchCompletionHandler 代表下面的代理方法

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

didReceiveNotificationResponse 代表下面的代理方法

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler

推送模式如下图表格所示:

设置 "content-available" = 1 是否实现代理方法 是否弹窗 是否需要点击弹窗 执行的方法
App前台 fetchCompletionHandler
didReceiveNotificationResponse
fetchCompletionHandler
fetchCompletionHandler
App后台 fetchCompletionHandler
didReceiveNotificationResponse
fetchCompletionHandler
fetchCompletionHandler
App杀死 fetchCompletionHandler
didReceiveNotificationResponse
fetchCompletionHandler
fetchCompletionHandler

iOS10以下设备的推送模式如下
// iOS 9 远程推送和后台推送都走这里 app杀死的情况需要点击弹窗 后台模式也会弹窗(需要点击)前台不弹窗 直接执行 走fetchCompletionHandler方法
// 前台模式设置了"content-available" = 1; 与否 前台不弹窗 直接执行
// 后台模式设置了"content-available" = 1; 弹窗 直接执行 不设置 弹窗 需要点击执行
// App杀死设置了"content-available" = 1; 与否 弹窗 都需要点击执行

推送调试

image.png
  • didReceiveIncomingPushWithPayload这个代理方法中获取的token 添加到 Easy APNs Provider
  • 选择推送的证书
  • 点击开始连接 gateway.sanbox.push.apple.com 对应的是开发证书, gateway.push.apple.com 对应的是生产证书
  • 然后就可以点击发送推送即可

软件不太好找 这里给你们分享下
链接: https://pan.baidu.com/s/16INLhg3V6CuVU5pJjDqptQ 提取码: wc6h 复制这段内容后打开百度网盘手机App,操作更方便哦

点个赞再走哦

你可能感兴趣的:(iOS 10推送使用总结)