关于iOSpush我们一般都会使用一些第三方SDK。最近因为项目需求需要使用系统push。这里总结下系统push的一些知识点:
关于push的证书这里就不介绍了。服务器方面:只需要把p12证书给到就行。
1、客户端注册、获取deviceToken
证书配置好了,下一步我们要获取deviceToken,用于推送到客户端设备。这个deviceToken也需要上传给服务器,否则无法push。
由于iOS10及以上把本地通知和远程通知都集成在了UserNotifications库里面,所以register push我们需要适配下系统版本:
- (void)registerSystemPushWithApplication:(UIApplication *)application
{
//iOS10及以上使用UserNotifications框架
if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10,0,0}]){
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
}
}];
}
else{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[application registerUserNotificationSettings:settings];
}
// 注册获得device Token
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
注册成功之后,会在Appdelegate里面输出deviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@"token:%@",deviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"push register error:%@",error);
}
注意(注册失败):
1、确认证书没有问题
2、使用真机
3、如下图,push Noti需要打开开关
客户端接收push消息
接收也需要按系统来分别处理,iOS7以上10以下
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
UIApplicationState state = [UIApplication sharedApplication].applicationState;
if (state == UIApplicationStateActive) {
//app在前台
[[SystemPushManage sharedSystemPushManage] activePushControllerWithUserInfo:userInfo];
}
else if (state == UIApplicationStateInactive){
[[SystemPushManage sharedSystemPushManage] backgroundPushControllerWithUserInfo:userInfo];
}
DLog(@"iOS7及以上系统,收到通知:%@", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
关于iOS10及以上请查看这个DEMO