概述
iOS中的通知包括本地推送通知和遠(yuǎn)程推送通知崔慧,兩者在iOS系統(tǒng)中都可以通過彈出橫幅的形式來提醒用戶鞠苟,點(diǎn)擊橫幅會(huì)打開應(yīng)用毛好。在iOS 10及之后版本的系統(tǒng)中,還支持通知擴(kuò)展功能(UNNotificationServiceExtension躏救、UNNotificationContentExtension
),下面就來詳細(xì)介紹iOS推送通知的相關(guān)功能及操作螟蒸。
一盒使、本地推送通知
本地推送通知是由本地應(yīng)用觸發(fā)的,是基于時(shí)間的通知形式七嫌,一般用于鬧鐘定時(shí)少办、待辦事項(xiàng)等提醒功能。發(fā)送本地推送通知的大體步驟如下:
(1)注冊本地通知诵原;
(2)創(chuàng)建本地通知相關(guān)變量英妓,并初始化;
(3)設(shè)置處理通知的時(shí)間fireDate
绍赛;
(4)設(shè)置通知的內(nèi)容:通知標(biāo)題蔓纠、通知聲音、圖標(biāo)數(shù)字等吗蚌;
(5)設(shè)置通知傳遞的參數(shù)userInfo
腿倚,該字典內(nèi)容可自定義(可選);
(6)添加這個(gè)本地通知到UNUserNotificationCenter
蚯妇。
1. 注冊本地推送通知
- (void)sendLocalNotification {
NSString *title = @"通知-title";
NSString *sutitle = @"通知-subtitle";
NSString *body = @"通知-body";
NSInteger badge = 1;
NSInteger timeInteval = 5;
NSDictionary *userInfo = @{@"id": @"LOCAL_NOTIFY_SCHEDULE_ID"};
if (@available(iOS 10.0, *)) {
// 1.創(chuàng)建通知內(nèi)容
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
[content setValue:@(YES) forKeyPath:@"shouldAlwaysAlertWhileAppIsForeground"];
content.sound = [UNNotificationSound defaultSound];
content.title = title;
content.subtitle = subtitle;
content.body = body;
content.badge = @(badge);
content.userInfo = userInfo;
// 2.設(shè)置通知附件內(nèi)容
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"logo_img_02@2x" ofType:@"png"];
UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"att1" URL:[NSURL fileURLWithPath:path] options:nil error:&error];
if (error) {
NSLog(@"attachment error %@", error);
}
content.attachments = @[att];
content.launchImageName = @"icon_certification_status1@2x";
// 3.設(shè)置聲音
UNNotificationSound *sound = [UNNotificationSound soundNamed:@"sound01.wav"];// [UNNotificationSound defaultSound];
content.sound = sound;
// 4.觸發(fā)模式
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:timeInteval repeats:NO];
// 5.設(shè)置UNNotificationRequest
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:LocalNotiReqIdentifer content:content trigger:trigger];
// 6.把通知加到UNUserNotificationCenter, 到指定觸發(fā)點(diǎn)會(huì)被觸發(fā)
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];
} else {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 1.設(shè)置觸發(fā)時(shí)間(如果要立即觸發(fā)敷燎,無需設(shè)置)
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
// 2.設(shè)置通知標(biāo)題
localNotification.alertBody = title;
// 3.設(shè)置通知?jiǎng)幼靼粹o的標(biāo)題
localNotification.alertAction = @"查看";
// 4.設(shè)置提醒的聲音
localNotification.soundName = @"sound01.wav";// UILocalNotificationDefaultSoundName;
// 5.設(shè)置通知的 傳遞的userInfo
localNotification.userInfo = userInfo;
// 6.在規(guī)定的日期觸發(fā)通知
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// 7.立即觸發(fā)一個(gè)通知
//[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}
}
2. 取消本地推送通知
- (void)cancelLocalNotificaitons {
// 取消一個(gè)特定的通知
NSArray *notificaitons = [[UIApplication sharedApplication] scheduledLocalNotifications];
// 獲取當(dāng)前所有的本地通知
if (!notificaitons || notificaitons.count <= 0) { return; }
for (UILocalNotification *notify in notificaitons) {
if ([[notify.userInfo objectForKey:@"id"] isEqualToString:@"LOCAL_NOTIFY_SCHEDULE_ID"]) {
if (@available(iOS 10.0, *)) {
[[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[LocalNotiReqIdentifer]];
} else {
[[UIApplication sharedApplication] cancelLocalNotification:notify];
}
break;
}
}
// 取消所有的本地通知
//[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
3. AppDelegate中的回調(diào)方法
在上面的代碼中我們設(shè)置了userInfo
暂筝,在iOS中收到并點(diǎn)擊通知,則會(huì)自動(dòng)打開應(yīng)用硬贯。但是在不同版本的iOS系統(tǒng)中回調(diào)方式有所差異焕襟,如下:
- 系統(tǒng)版本 < iOS 10
// 如果App已經(jīng)完全退出:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
// 當(dāng)App已經(jīng)完全退出時(shí),獲取userInfo參數(shù)過程如下:
// NSDictionary *userInfoLocal = (NSDictionary *)[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// NSDictionary *userInfoRemote = (NSDictionary *)[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
// 如果App還在運(yùn)行(前臺or后臺)
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
- 系統(tǒng)版本 >= iOS 10
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#pragma mark - UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED;
#endif
4. 實(shí)現(xiàn)效果
-
app向用戶請求推送通知權(quán)限的提示彈窗:
請求推送通知權(quán)限的提示彈窗 -
app處于不同狀態(tài)(前臺饭豹、后臺鸵赖、鎖屏)時(shí)彈出通知的效果:
app處于前臺
app處于后臺
鎖屏
PS:
- 當(dāng)用戶拒絕授權(quán)推送通知時(shí),
app
無法接收通知墨状;(用戶可以到設(shè)置->通知->相應(yīng)app
卫漫,手動(dòng)設(shè)置通知選項(xiàng))- 通知的聲音在代碼中指定,由系統(tǒng)播放肾砂,時(shí)長必須在
30s
內(nèi)列赎,否則將被默認(rèn)聲音替換,并且自定義聲音文件必須放到main bundle
中镐确。- 本地通知有數(shù)量限制包吝,超過一定數(shù)量(64個(gè))將被系統(tǒng)忽略(數(shù)據(jù)來源于網(wǎng)絡(luò),具體時(shí)間間隔待驗(yàn)證)源葫。
二诗越、遠(yuǎn)程推送通知
遠(yuǎn)程推送通知是通過蘋果的APNs(
Apple Push Notification service
)發(fā)送到app
,而APNs
必須先知道用戶設(shè)備的令牌(device token
)息堂。在啟動(dòng)時(shí)嚷狞,app
與APNs
通信并接收device token
,然后將其轉(zhuǎn)發(fā)到App Server
荣堰,App Server
將該令牌和要發(fā)送的通知消息發(fā)送至APNs
床未。
PS:蘋果官網(wǎng)APNs概述
遠(yuǎn)程推送通知的傳遞過程涉及幾個(gè)關(guān)鍵組件:
- App Server
- Apple推送通知服務(wù)(APNs)
- 用戶的設(shè)備(iPhone、iPad振坚、iTouch薇搁、Mac等)
- 相應(yīng)的app
蘋果官方提供的遠(yuǎn)程推送通知的傳遞示意圖如下:
各關(guān)鍵組件之間的交互細(xì)節(jié):
開發(fā)遠(yuǎn)程推送功能首先要設(shè)置正確的推送證書和權(quán)限,步驟如下:
1)根據(jù)工程的Bundle Identifier
渡八,在蘋果開發(fā)者平臺中創(chuàng)建同名App ID
啃洋,并勾選Push Notifications
服務(wù);
2)在工程的“Capabilities”中設(shè)置Push Notifications
為ON
屎鳍;
3)遠(yuǎn)程推送必須使用真機(jī)調(diào)試宏娄,因?yàn)槟M器無法獲取得到device token
。在設(shè)置好證書和權(quán)限后逮壁,按照以下步驟開發(fā)遠(yuǎn)程推送功能:
1. 注冊遠(yuǎn)程通知
// iOS 8及以上版本的遠(yuǎn)程推送通知注冊
- (void)registerRemoteNotifications
{
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
NSLog(@"request authorization failed!");
}
}];
} else {
UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}
2. App獲取device token
- 在注冊遠(yuǎn)程通知后绝编,獲取
device token
的回調(diào)方法:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
- 獲取
device token
失敗的回調(diào)方法:
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
3. app將device token發(fā)送給App Server
只有蘋果公司知道device token
的生成算法,保證唯一,device token
在app卸載后重裝等情況時(shí)會(huì)變化十饥,因此為確保device token
變化后app仍然能夠正常接收服務(wù)器端發(fā)送的通知窟勃,建議每次啟動(dòng)應(yīng)用都將獲取到的device token
傳給App Server
。
4. App Server將device token和要推送的消息發(fā)送給APNs
將指定的device token
和消息內(nèi)容發(fā)送給APNs
時(shí)逗堵,必須按照蘋果官方的消息格式組織消息內(nèi)容秉氧。
PS:遠(yuǎn)程通知消息的字段、創(chuàng)建遠(yuǎn)程通知消息
消息格式:
{"aps":{"alert":{"title":"通知的title","subtitle":"通知的subtitle","body":"通知的body","title-loc-key":"TITLE_LOC_KEY","title-loc-args":["t_01","t_02"],"loc-key":"LOC_KEY","loc-args":["l_01","l_02"]},"sound":"sound01.wav","badge":1,"mutable-content":1,"category": "realtime"},"msgid":"123"}
5. APNs根據(jù)device token查找相應(yīng)設(shè)備蜒秤,并推送消息
一般情況APNs
可以根據(jù)deviceToken
將消息成功推送到相應(yīng)設(shè)備中汁咏,但也存在用戶卸載程序等導(dǎo)致推送消息失敗的情況,這時(shí)App Server
會(huì)收到APNs
返回的錯(cuò)誤信息)作媚。
6. AppDelegate中的回調(diào)方法
// iOS<10時(shí)攘滩,且app被完全殺死
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
// 注:iOS10以上如果不使用UNUserNotificationCenter時(shí),也將走此回調(diào)方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
// 支持iOS7及以上系統(tǒng)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;
// iOS>=10: app在前臺獲取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler;
// iOS>=10: 點(diǎn)擊通知進(jìn)入app時(shí)觸發(fā)(殺死/切到后臺喚起)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler;
在AppDelegate中注冊遠(yuǎn)程推送通知并解析通知數(shù)據(jù)的完整代碼如下:
#import "AppDelegate.h"
#import "ViewController.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif
@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
ViewController *controller = [[ViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
_window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
[_window setRootViewController:nav];
[_window makeKeyAndVisible];
////注冊本地推送通知(具體操作在ViewController中)
//[self registerLocalNotification];
// 注冊遠(yuǎn)程推送通知
[self registerRemoteNotifications];
return YES;
}
- (void)registerLocalNotification {
if (@available(iOS 10.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];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
}
- (void)registerRemoteNotifications
{
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
NSLog(@"request authorization failed!");
}
}];
} else {
UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
NSLog(@"didRegisterUserNotificationSettings");
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
NSLog(@"app收到本地推送(didReceiveLocalNotification:):%@", notification.userInfo);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// 獲取并處理deviceToken
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"DeviceToken:%@\n", token);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"didFailToRegisterForRemoteNotificationsWithError: %@", error.description);
}
// 注:iOS10以上如果不使用UNUserNotificationCenter時(shí)纸泡,也將走此回調(diào)方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// iOS6及以下系統(tǒng)
if (userInfo) {
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {// app位于前臺通知
NSLog(@"app位于前臺通知(didReceiveRemoteNotification:):%@", userInfo);
} else {// 切到后臺喚起
NSLog(@"app位于后臺通知(didReceiveRemoteNotification:):%@", userInfo);
}
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler NS_AVAILABLE_IOS(7_0) {
// iOS7及以上系統(tǒng)
if (userInfo) {
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
NSLog(@"app位于前臺通知(didReceiveRemoteNotification:fetchCompletionHandler:):%@", userInfo);
} else {
NSLog(@"app位于后臺通知(didReceiveRemoteNotification:fetchCompletionHandler:):%@", userInfo);
}
}
completionHandler(UIBackgroundFetchResultNewData);
}
#pragma mark - iOS>=10 中收到推送消息
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
API_AVAILABLE(ios(10.0)){
NSDictionary * userInfo = notification.request.content.userInfo;
if (userInfo) {
NSLog(@"app位于前臺通知(willPresentNotification:):%@", userInfo);
}
completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
API_AVAILABLE(ios(10.0)){
NSDictionary * userInfo = response.notification.request.content.userInfo;
if (userInfo) {
NSLog(@"點(diǎn)擊通知進(jìn)入App時(shí)觸發(fā)(didReceiveNotificationResponse:):%@", userInfo);
}
completionHandler();
}
#endif
@end
7. 使用Pusher工具模擬App Server推送通知
Pusher和SmartPush等工具一樣漂问,是優(yōu)秀的遠(yuǎn)程推送測試工具,工具界面如下:
- Pusher的使用步驟說明:
1)選擇p12
格式的推送證書女揭;
2)設(shè)置是否為測試環(huán)境(默認(rèn)勾選為測試環(huán)境蚤假,由于推送證書分為測試證書和生產(chǎn)證書,并且蘋果的APNs
也分為測試和生產(chǎn)兩套環(huán)境吧兔,因此Pusher
需要手動(dòng)勾選推送環(huán)境)磷仰;
3)輸入device token
;
4)輸入符合蘋果要求格式的aps
字符串境蔼;
5)執(zhí)行推送灶平。
效果如下:
點(diǎn)擊橫幅打開app,在回調(diào)方法中獲取到的
json
串如下:
PS:
- 要使用遠(yuǎn)程推送通知功能箍土,需要至少啟動(dòng)app一次逢享;
- 設(shè)備不連網(wǎng),是無法注冊遠(yuǎn)程推送通知的涮帘;
- 推送過程中aps串可在適當(dāng)位置添加自定義字段拼苍,消息上限為
4 KB
笑诅。
三调缨、iOS 通知擴(kuò)展
iOS 10及之后的推送通知具有擴(kuò)展功能,包括兩個(gè)方面:
- 通知服務(wù)擴(kuò)展(UNNotificationServiceExtension)吆你,是在收到通知后且展示通知前允許開發(fā)者做一些事情弦叶,比如添加附件、加載網(wǎng)絡(luò)請求等妇多。點(diǎn)擊查看官網(wǎng)文檔
- 通知內(nèi)容擴(kuò)展(UNNotificationContentExtension)伤哺,是在展示通知時(shí)展示一個(gè)自定義的用戶界面。點(diǎn)擊查看官網(wǎng)文檔
1. 創(chuàng)建UNNotificationServiceExtension和UNNotificationContentExtension:
注意:
- target支持的iOS版本為10.0及以上,且當(dāng)前系統(tǒng)支持target版本立莉。
2. 通知服務(wù)擴(kuò)展UNNotificationServiceExtension
在NotificationService.m文件中绢彤,有兩個(gè)回調(diào)方法:
// 系統(tǒng)接到通知后,有最多30秒在這里重寫通知內(nèi)容(如下載附件并更新通知)
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler;
// 處理過程超時(shí)蜓耻,則收到的通知直接展示出來
- (void)serviceExtensionTimeWillExpire;
在通知服務(wù)擴(kuò)展中加載網(wǎng)絡(luò)請求茫舶,代碼如下:
#import "NotificationService.h"
#import <AVFoundation/AVFoundation.h>
@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@end
@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
//// Modify the notification content here...
self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [ServiceExtension modified]", self.bestAttemptContent.title];
// 設(shè)置UNNotificationAction
UNNotificationAction * actionA =[UNNotificationAction actionWithIdentifier:@"ActionA" title:@"A_Required" options:UNNotificationActionOptionAuthenticationRequired];
UNNotificationAction * actionB = [UNNotificationAction actionWithIdentifier:@"ActionB" title:@"B_Destructive" options:UNNotificationActionOptionDestructive];
UNNotificationAction * actionC = [UNNotificationAction actionWithIdentifier:@"ActionC" title:@"C_Foreground" options:UNNotificationActionOptionForeground];
UNTextInputNotificationAction * actionD = [UNTextInputNotificationAction actionWithIdentifier:@"ActionD"
title:@"D_InputDestructive"
options:UNNotificationActionOptionDestructive
textInputButtonTitle:@"Send"
textInputPlaceholder:@"input some words here ..."];
NSArray *actionArr = [[NSArray alloc] initWithObjects:actionA, actionB, actionC, actionD, nil];
NSArray *identifierArr = [[NSArray alloc] initWithObjects:@"ActionA", @"ActionB", @"ActionC", @"ActionD", nil];
UNNotificationCategory * notficationCategory = [UNNotificationCategory categoryWithIdentifier:@"QiShareCategoryIdentifier"
actions:actionArr
intentIdentifiers:identifierArr
options:UNNotificationCategoryOptionCustomDismissAction];
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObject:notficationCategory]];
// 設(shè)置categoryIdentifier
self.bestAttemptContent.categoryIdentifier = @"QiShareCategoryIdentifier";
// 加載網(wǎng)絡(luò)請求
NSDictionary *userInfo = self.bestAttemptContent.userInfo;
NSString *mediaUrl = userInfo[@"media"][@"url"];
NSString *mediaType = userInfo[@"media"][@"type"];
if (!mediaUrl.length) {
self.contentHandler(self.bestAttemptContent);
} else {
[self loadAttachmentForUrlString:mediaUrl withType:mediaType completionHandle:^(UNNotificationAttachment *attach) {
if (attach) {
self.bestAttemptContent.attachments = [NSArray arrayWithObject:attach];
}
self.contentHandler(self.bestAttemptContent);
}];
}
}
- (void)loadAttachmentForUrlString:(NSString *)urlStr withType:(NSString *)type completionHandle:(void(^)(UNNotificationAttachment *attach))completionHandler
{
__block UNNotificationAttachment *attachment = nil;
NSURL *attachmentURL = [NSURL URLWithString:urlStr];
NSString *fileExt = [self getfileExtWithMediaType:type];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session downloadTaskWithURL:attachmentURL completionHandler:^(NSURL *temporaryFileLocation, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"加載多媒體失敗 %@", error.localizedDescription);
} else {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *localURL = [NSURL fileURLWithPath:[temporaryFileLocation.path stringByAppendingString:fileExt]];
[fileManager moveItemAtURL:temporaryFileLocation toURL:localURL error:&error];
// 自定義推送UI需要
NSMutableDictionary * dict = [self.bestAttemptContent.userInfo mutableCopy];
[dict setObject:[NSData dataWithContentsOfURL:localURL] forKey:@"image"];
self.bestAttemptContent.userInfo = dict;
NSError *attachmentError = nil;
attachment = [UNNotificationAttachment attachmentWithIdentifier:@"QiShareCategoryIdentifier" URL:localURL options:nil error:&attachmentError];
if (attachmentError) {
NSLog(@"%@", attachmentError.localizedDescription);
}
}
completionHandler(attachment);
}] resume];
}
- (NSString *)getfileExtWithMediaType:(NSString *)mediaType {
NSString *fileExt = mediaType;
if ([mediaType isEqualToString:@"image"]) {
fileExt = @"jpg";
}
if ([mediaType isEqualToString:@"video"]) {
fileExt = @"mp4";
}
if ([mediaType isEqualToString:@"audio"]) {
fileExt = @"mp3";
}
return [@"." stringByAppendingString:fileExt];
}
- (void)serviceExtensionTimeWillExpire {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
self.contentHandler(self.bestAttemptContent);
}
@end
消息內(nèi)容格式:
{"aps":{"alert":{"title":"Title...","subtitle":"Subtitle...","body":"Body..."},"sound":"default","badge": 1,"mutable-content": 1,"category": "QiShareCategoryIdentifier",},"msgid":"123","media":{"type":"image","url":"https://www.fotor.com/images2/features/photo_effects/e_bw.jpg"}}
PS:
- 加載并處理附件時(shí)間上限為30秒,否則刹淌,通知按系統(tǒng)默認(rèn)形式彈出饶氏;
- UNNotificationAttachment的url接收的是本地文件的url;
- 服務(wù)端在處理推送內(nèi)容時(shí)有勾,最好加上媒體類型字段疹启;
- aps字符串中的mutable-content字段需要設(shè)置為1;
- 在對NotificationService進(jìn)行debug時(shí)蔼卡,需要在Xcode頂欄選擇編譯運(yùn)行的target為NotificationService喊崖,否則無法進(jìn)行實(shí)時(shí)debug。
3. 通知內(nèi)容擴(kuò)展UNNotificationContentExtension
通知內(nèi)容擴(kuò)展界面NotificationViewController的結(jié)構(gòu)如下:
- 設(shè)置actions:
從NotificationViewController直接繼承于ViewController菲宴,因此可以在這個(gè)類中重寫相關(guān)方法贷祈,來修改界面的相關(guān)布局及樣式。在這個(gè)界面展開之前喝峦,用戶可以通過UNNotificationAction與相應(yīng)推送通知交互势誊,但是用戶和這個(gè)通知內(nèi)容擴(kuò)展界面無法直接交互。 - 設(shè)置category:
推送通知內(nèi)容中的category字段谣蠢,與UNNotificationContentExtension的info.plist中UNNotificationExtensionCategory字段的值要匹配粟耻,系統(tǒng)才能找到自定義的UI。
在aps串中直接設(shè)置category字段眉踱,例如:
{ "aps":{ "alert":"Testing...(0)","badge":1,"sound":"default","category":"QiShareCategoryIdentifier"}}
在NotificationService.m中設(shè)置category的值如下:
self.bestAttemptContent.categoryIdentifier = @"QiShareCategoryIdentifier";
info.plist中關(guān)于category的配置如下:
- UNNotificationContentExtension協(xié)議:NotificationViewController 中生成時(shí)默認(rèn)實(shí)現(xiàn)了阳懂。
簡單的英文注釋很明了:
// This will be called to send the notification to be displayed by
// the extension. If the extension is being displayed and more related
// notifications arrive (eg. more messages for the same conversation)
// the same method will be called for each new notification.
- (void)didReceiveNotification:(UNNotification *)notification;
// If implemented, the method will be called when the user taps on one
// of the notification actions. The completion handler can be called
// after handling the action to dismiss the notification and forward the
// action to the app if necessary.
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion
// Called when the user taps the play or pause button.
- (void)mediaPlay;
- (void)mediaPause;
- UNNotificationAttachment:attachment支持
1)音頻5M(kUTTypeWaveformAudio/kUTTypeMP3/kUTTypeMPEG4Audio/kUTTypeAudioInterchangeFileFormat)
2)圖片10M(kUTTypeJPEG/kUTTypeGIF/kUTTypePNG)
3)視頻50M(kUTTypeMPEG/kUTTypeMPEG2Video/kUTTypeMPEG4/kUTTypeAVIMovie)
4. 自定義內(nèi)容擴(kuò)展界面與內(nèi)容擴(kuò)展功能聯(lián)合使用時(shí)眨猎,代碼如下:
#import "NotificationViewController.h"
#import <UserNotifications/UserNotifications.h>
#import <UserNotificationsUI/UserNotificationsUI.h>
#define Margin 15
@interface NotificationViewController () <UNNotificationContentExtension>
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UILabel *subLabel;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *hintLabel;
@end
@implementation NotificationViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGPoint origin = self.view.frame.origin;
CGSize size = self.view.frame.size;
self.label = [[UILabel alloc] initWithFrame:CGRectMake(Margin, Margin, size.width-Margin*2, 30)];
self.label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:self.label];
self.subLabel = [[UILabel alloc] initWithFrame:CGRectMake(Margin, CGRectGetMaxY(self.label.frame)+10, size.width-Margin*2, 30)];
self.subLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:self.subLabel];
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(Margin, CGRectGetMaxY(self.subLabel.frame)+10, 100, 100)];
[self.view addSubview:self.imageView];
self.hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(Margin, CGRectGetMaxY(self.imageView.frame)+10, size.width-Margin*2, 20)];
[self.hintLabel setText:@"我是hintLabel"];
[self.hintLabel setFont:[UIFont systemFontOfSize:14]];
[self.hintLabel setTextAlignment:NSTextAlignmentLeft];
[self.view addSubview:self.hintLabel];
self.view.frame = CGRectMake(origin.x, origin.y, size.width, CGRectGetMaxY(self.imageView.frame)+Margin);
// 設(shè)置控件邊框顏色
[self.label.layer setBorderColor:[UIColor redColor].CGColor];
[self.label.layer setBorderWidth:1.0];
[self.subLabel.layer setBorderColor:[UIColor greenColor].CGColor];
[self.subLabel.layer setBorderWidth:1.0];
[self.imageView.layer setBorderWidth:2.0];
[self.imageView.layer setBorderColor:[UIColor blueColor].CGColor];
[self.view.layer setBorderWidth:2.0];
[self.view.layer setBorderColor:[UIColor cyanColor].CGColor];
}
- (void)didReceiveNotification:(UNNotification *)notification {
self.label.text = notification.request.content.title;
self.subLabel.text = [NSString stringWithFormat:@"%@ [ContentExtension modified]", notification.request.content.subtitle];
NSData *data = notification.request.content.userInfo[@"image"];
UIImage *image = [UIImage imageWithData:data];
[self.imageView setImage:image];
}
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion {
[self.hintLabel setText:[NSString stringWithFormat:@"觸發(fā)了%@", response.actionIdentifier]];
if ([response.actionIdentifier isEqualToString:@"ActionA"]) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
completion(UNNotificationContentExtensionResponseOptionDismiss);
});
} else if ([response.actionIdentifier isEqualToString:@"ActionB"]) {
} else if ([response.actionIdentifier isEqualToString:@"ActionC"]) {
} else if ([response.actionIdentifier isEqualToString:@"ActionD"]) {
} else {
completion(UNNotificationContentExtensionResponseOptionDismiss);
}
completion(UNNotificationContentExtensionResponseOptionDoNotDismiss);
}
@end
手機(jī)收到通知時(shí)的展示(aps串以上面第2點(diǎn)中提到的“消息內(nèi)容格式”為例)
說明:
- 服務(wù)擴(kuò)展target和內(nèi)容擴(kuò)展target在配置中所支持的系統(tǒng)版本要在iOS10及以上钮孵;
- 自定義視圖的大小可以通過設(shè)置NotificationViewController的preferredContentSize大小來控制,但是用戶體驗(yàn)稍顯突兀婿禽,可以通過設(shè)置info.plist中的UNNotificationExtensionInitialContentSizeRatio屬性的值來優(yōu)化赏僧;
- contentExtension中的info.plist中NSExtension下的NSExtensionAttributes字段下可以配置以下屬性的值,UNNotificationExtensionCategory:表示自定義內(nèi)容假面可以識別的category扭倾,可以為數(shù)組淀零,也即可以為這個(gè)content綁定多個(gè)通知;UNNotificationExtensionInitialContentSizeRatio:默認(rèn)的UI界面的寬高比膛壹;UNNotificationExtensionDefaultContentHidden:是否顯示系統(tǒng)默認(rèn)的標(biāo)題欄和內(nèi)容驾中,可選參數(shù)唉堪;UNNotificationExtensionOverridesDefaultTitle:是否讓系統(tǒng)采用消息的標(biāo)題作為通知的標(biāo)題,可選參數(shù)肩民。
- 處理通知內(nèi)容擴(kuò)展的過程中關(guān)于identifier的設(shè)置共有五處(UNNotificationAction唠亚、UNNotificationCategory、bestAttemptContent持痰、contentExtension中的info.plist中趾撵,aps字符串中),請區(qū)別不同identifier的作用共啃。
- 兩個(gè)擴(kuò)展聯(lián)合使用占调,在XCode中選擇當(dāng)前target,才能打斷點(diǎn)看到相應(yīng)log信息移剪。
工程源碼:GitHub地址