AppDelegate中导入头文件:
#import <UserNotifications/UserNotifications.h>
3.在application:didFinishLaunchingWithOptions方法中, 注册远程通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//请求通知权限, 本地和远程共用
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
NSLog(@"请求成功");
} else {
NSLog(@"请求失败");
}
}];
//注册远程通知
[[UIApplication sharedApplication] registerForRemoteNotifications];
//设置通知的代理
center.delegate = self;
return YES;
}
4.在接收远程推送的DeviceToken方法中, 获取Token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//将来需要将此Token上传给后台服务器
NSLog(@"token:%@", deviceToken);
}
二、 iOS10远程推送通知的处理方法
当点击了推送后, 如果你希望进行处理. 那么在iOS10中, 还需要设置UNUserNotificationCenter的delegate, 并遵守UNUserNotificationCenterDelegate协议.
以及实现下面实现3个方法, 用于处理点击通知时的不同情况的处理
willPresentNotification:withCompletionHandler 用于前台运行
didReceiveNotificationResponse:withCompletionHandler 用于后台及程序退出
didReceiveRemoteNotification:fetchCompletionHandler用于静默推送
//设置通知的代理
center.delegate = self;
1.前台运行 会调用的方法
前台运行: 指的是程序正在运行中, 用户能看见程序的界面.
iOS10会出现通知横幅, 而在以前的框架中, 前台运行时, 不会出现通知的横幅.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
NSDictionary *userInfo = notification.request.content.userInfo;
//前台运行推送 显示红色Label
[self showLabelWithUserInfo:userInfo color:[UIColor redColor]];
//可以设置当收到通知后, 有哪些效果呈现(声音/提醒/数字角标)
completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}










