此系列工程开发环境为xcode 8.2
1、创建工程,开启通知权限。开启后如果确认证书和自己的Boundle ID设置正确的情况下,第一个出现红色的叉叉,可以尝试clear之后退出xcode
2、创建通知的代理管理类(NotificationHandle),这样可以将代码分类管理
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>
@interface NotificationHandle : NSObject<UNUserNotificationCenterDelegate>
+(NotificationHandle *) shareInstance;
-(void)authorizationPushNotificaton:(UIApplication *)application;
@end
@implementation NotificationHandle
+(NotificationHandle *) shareInstance
{
static NotificationHandle *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[[self class] alloc] init];
});
return instance;
}
-(void)authorizationPushNotificaton:(UIApplication *)application
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self; //必须写代理
[center requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay completionHandler:^(BOOL granted, NSError * _Nullable error) {
//注册之后的回调
if (!error && granted) {
NSLog(@"注册成功...");
}
else{
NSLog(@"注册失败...");
}
}];
//获取注册之后的权限设置
//注意UNNotificationSettings是只读对象哦,不能直接修改!
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
NSLog(@"通知配置信息:\n%@",settings);
}];
//注册通知获取token
[application registerForRemoteNotifications];
}
#pragma mark UNUserNotificationCenterDelegate
//收到通知
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
//收到推送的请求
UNNotificationRequest *request = notification.request;
//收到的内容
UNNotificationContent *content = request.content;
//收到用户的基本信息
NSDictionary *userInfo = content.userInfo;
//收到消息的角标
NSNumber *badge = content.badge;
//收到消息的body
NSString *body = content.body;
//收到消息的声音
UNNotificationSound *sound = content.sound;
//推送消息的副标题
NSString *subtitle = content.subtitle;
//推送消息的标题
NSString *title = content.title;
if ([notification.request.trigger isKindOfClass:[UNNotificationTrigger class]]) {
NSLog(@"前台收到通知:%@\n",userInfo);
}
else{
NSLog(@"前台收到通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@}",body,title,subtitle,badge,sound,userInfo);
}
//不管前台后台状态下。推送消息的横幅都可以展示出来!有Badge、Sound、Alert三种类型可以设置
completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}
//app通知的点击事件
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
//收到推送的请求
UNNotificationRequest *request = response.notification.request;
//收到的内容
UNNotificationContent *content = request.content;
//收到用户的基本信息
NSDictionary *userInfo = content.userInfo;
//收到消息的角标
NSNumber *badge = content.badge;
//收到消息的body
NSString *body = content.body;
//收到消息的声音
UNNotificationSound *sound = content.sound;
//推送消息的副标题
NSString *subtitle = content.subtitle;
//推送消息的标题
NSString *title = content.title;
if ([response.notification.request.trigger isKindOfClass:[UNNotificationTrigger class]]) {
NSLog(@"点击了通知:%@\n",userInfo);
}
else{
NSLog(@"通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@}",body,title,subtitle,badge,sound,userInfo);
}
completionHandler();
} @end
3、在AppDelegate中申请授权
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
_window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
RootViewController *rootVC = [[RootViewController alloc]init];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:rootVC];
_window.rootViewController = nav;
[_window makeKeyWindow];
[UNUserNotificationCenter currentNotificationCenter].delegate = [NotificationHandle shareInstance];
[[NotificationHandle shareInstance] authorizationPushNotificaton:application];
return YES;
}
4、实现注册token成功和失败的处理
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *deviceString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
deviceString = [deviceString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"远端获取的deviceToken\n%@",deviceString);
//存储得到的token,后面备用
[[NSUserDefaults standardUserDefaults] setValue:deviceString forKey:@"deviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(@"获取token失败:%@\n",error.localizedDescription);
}
5、启动app,弹出通知授权,允许之后就可以进到授权信息界面实现获取授权信息了,界面UI自行布局,下面给出获取授权信息的关键代码
-(void)setData
{
self.deviceTokenLabel.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"deviceToken"];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
__weak typeof(&*self) weakSelf = self;
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
weakSelf.centerLabel.text = [weakSelf getSettingDescribe:settings.notificationCenterSetting];
weakSelf.soundLabel.text = [weakSelf getSettingDescribe:settings.soundSetting];
weakSelf.badgeLabel.text = [weakSelf getSettingDescribe:settings.badgeSetting];
weakSelf.lockScreenLabel.text = [weakSelf getSettingDescribe:settings.lockScreenSetting];
weakSelf.alertLabel.text = [weakSelf getSettingDescribe:settings.alertSetting];
weakSelf.carPlayLabel.text = [weakSelf getSettingDescribe:settings.carPlaySetting];
weakSelf.alertStyleLabel.text = [weakSelf getAlertStyleDescribe:settings.alertStyle];
}];
}
-(NSString *)getAlertStyleDescribe:(NSInteger)alertStyle
{
NSString *backStr = @"";
switch (alertStyle) {
case 0:
backStr = @"UNAlertStyleNone";
break;
case 1:
backStr = @"UNAlertStyleBanner";
break;
case 2:
backStr = @"UNAlertStyleAlert";
break;
default:
backStr = @"UNKNOW";
break;
}
return backStr;
}
-(NSString *)getSettingDescribe:(NSInteger)setting
{
NSString *backStr = @"";
switch (setting) {
case 0:
backStr = @"NotSupported";
break;
case 1:
backStr = @"Disabled";
break;
case 2:
backStr = @"Enabled";
break;
default:
backStr = @"UNKNOW";
break;
}
return backStr;
}
6、最后运行的效果图如下