此係列工程開發環境爲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、最後運行的效果圖如下