UNNotificationServiceExtension 簡介:
UNNotificationServiceExtension 是iOS10
后推出的一個(gè)新特性:
從上面這張圖片我們可以發(fā)現(xiàn),在APNs
到App
推送中間添加Service Extension
,通過Service Extension
我們可以對推送內(nèi)容進(jìn)行處理,給用戶展示更為豐富的通知內(nèi)容顯示.那么為什么蘋果會在iOS10
后推出這個(gè)通知新特性呢?總結(jié)如下:
- 安全:
蘋果總是把安全放在第一位,我們也知道蘋果在iOS 9
開始鼓勵我們使用更為安全的https協(xié)議.因?yàn)橹暗耐扑痛蟛糠侄际峭ㄟ^第三方機(jī)構(gòu)推送,如果讓心懷詭異的人進(jìn)行抓包,數(shù)據(jù)也會暴露出來,這樣我們可以在UNNotificationServiceExtension
類進(jìn)行數(shù)據(jù)的處理. - 通知欄的內(nèi)容展示更為豐富:
UNNotificationContentExtension
通知拓展類剩膘,可以給用戶展現(xiàn)出一個(gè)有著豐富內(nèi)容的通知,吸引用戶點(diǎn)擊通知進(jìn)入到App
.
我們新建一個(gè)UNNotificationServiceExtension
:
這樣在我們工程中就會看見一個(gè)文件夾,里面有2個(gè)文件,會默認(rèn)生成2個(gè)方法,上代碼:(下面實(shí)現(xiàn)在App進(jìn)程殺死或者正在使用會播報(bào)本地一段音頻文件音頻長度不要超過30s
蘋果限制了,否則無法播放音頻文件)
#import "NotificationService.h"
#import <AVFoundation/AVFAudio.h>
#import <AudioToolbox/AudioToolbox.h>
@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@property (nonatomic, strong) AVSpeechSynthesizer *aVSpeechSynthesizer;
@end
@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [哈哈]", self.bestAttemptContent.title];
self.bestAttemptContent.sound = nil;
NSDictionary *apns = self.bestAttemptContent.userInfo[@"aps"];
NSLog(@"apns = %@", apns);
if (apns) {
NSString *sound = apns[@"sound"][@"name"];
if (sound) {
NSString *path = [[NSBundle mainBundle] pathForResource:sound ofType:@"caf"];
static SystemSoundID soundID = 0;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
[[AVAudioSession sharedInstance] setActive:YES error:NULL];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
NSLog(@"播報(bào)完成");
});
}
}
self.contentHandler(self.bestAttemptContent);
}
- (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
接下來我們進(jìn)行測試,我使用極光進(jìn)行測試的 極光集成文檔,集成好之后,我們在極光后臺進(jìn)行推送的時(shí)候"附加字段"這個(gè)選項(xiàng)里面一定添加"mutable-content": "1"
纸型,否則可能會攔截通知失敗(官方文檔解釋),以后需要后臺推送的時(shí)候也要加上這個(gè)字段"mutable-content"
.
我在官網(wǎng)推送的自定義字段格式如下圖: