iOS10注册推送,兼容低版本
1,注册
- (void)startAuthority{
if (iOSVersionGreaterThanOrEqualTo(@"10")) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"succeeded!");
}
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}else{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}
2、接收消息
iOS10, iOS10+
收到远程推送使用这个方法接收通知
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
NSDictionary * userInfo = notification.request.content.userInfo;
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//应用处于后台时的远程推送接受
}else{
//应用处于前台时的本地推送接受
}
}
iOS10-
iOS10以下使用这个方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
}
注:如果两个接收通知的方法都同时实现了,那么iOS10的方法将不再执行】
另外,有些第三方的推送已经集成了注册代码,比如友盟推送,只需要调用
[UMessage registerForRemoteNotifications];
即可。