級別: ★★☆☆☆
標籤:「iOS通知擴展」「iOS推送擴展」「UNNotificationServiceExtension」「UNNotificationContentExtension」
做者: dac_1033
審校: QiShare團隊php
iOS10以後的通知具備擴展功能,能夠在系統收到通知、展現通知時作一些事情。下面是實現步驟要點介紹:git
在NotificationService.m文件中,有兩個方法:github
// 系統接到通知後,有最多30秒在這裏重寫通知內容(以下載附件並更新通知)
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler;
// 處理過程超時,則收到的通知直接展現出來
- (void)serviceExtensionTimeWillExpire;
複製代碼
代碼示例以下:數組
#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:@"%@ [modified]", self.bestAttemptContent.title];
// 注:爲通知下拉手動展開時,可添加多個事件
// UNNotificationActionOptions包含三個值UNNotificationActionOptionAuthenticationRequired、UNNotificationActionOptionDestructive、UNNotificationActionOptionForeground
UNNotificationAction * actionA =[UNNotificationAction actionWithIdentifier:@"ActionA" title:@"Required" options:UNNotificationActionOptionAuthenticationRequired];
UNNotificationAction * actionB = [UNNotificationAction actionWithIdentifier:@"ActionB" title:@"Destructive" options:UNNotificationActionOptionDestructive];
UNNotificationAction * actionC = [UNNotificationAction actionWithIdentifier:@"ActionC" title:@"Foreground" options:UNNotificationActionOptionForeground];
UNTextInputNotificationAction * actionD = [UNTextInputNotificationAction actionWithIdentifier:@"ActionD"
title:@"Input-Destructive"
options:UNNotificationActionOptionDestructive
textInputButtonTitle:@"Send"
textInputPlaceholder:@"input some words here ..."];
NSMutableArray *actionArr = [[NSMutableArray alloc] initWithObjects:actionA, actionB, actionC, actionD, nil];
if (actionArr.count) {
UNNotificationCategory * notficationCategory = [UNNotificationCategory categoryWithIdentifier:@"categoryNoOperationAction"
actions:actionArr
intentIdentifiers:@[@"ActionA",@"ActionB",@"ActionC",@"ActionD"]
options:UNNotificationCategoryOptionCustomDismissAction];
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObject:notficationCategory]];
}
// 注:1.通知擴展功能須在aps串中設置字段"mutable-content":1; 2.多媒體的字段能夠與appServer協議制定;
self.bestAttemptContent.categoryIdentifier = @"QiShareCategoryIdentifier";
NSDictionary *userInfo = self.bestAttemptContent.userInfo;
NSString *mediaUrl = [NSString stringWithFormat:@"%@", userInfo[@"media"][@"url"]];
if (!mediaUrl.length) {
self.contentHandler(self.bestAttemptContent);
}
else {
[self loadAttachmentForUrlString:mediaUrl withType:userInfo[@"media"][@"type"] 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 fileExtensionForMediaType:type];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session downloadTaskWithURL:attachmentURL completionHandler:^(NSURL *temporaryFileLocation, NSURLResponse *response, NSError *error) {
if (error != nil) {
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:@"" URL:localURL options:nil error:&attachmentError];
if (attachmentError) {
NSLog(@"%@", attachmentError.localizedDescription);
}
}
completionHandler(attachment);
}] resume];
}
- (NSString *)fileExtensionForMediaType:(NSString *)type {
NSString *ext = type;
if ([type isEqualToString:@"image"]) {
ext = @"jpg";
}
else if ([type isEqualToString:@"video"]) {
ext = @"mp4";
}
else if ([type isEqualToString:@"audio"]) {
ext = @"mp3";
}
return [@"." stringByAppendingString:ext];
}
- (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
複製代碼
aps串格式: {"aps":{"alert":{"title":"Title...","subtitle":"Subtitle...","body":"Body..."},"sound":"default","badge": 1,"mutable-content": 1,"category": "realtime",},"msgid":"123","media":{"type":"image","url":"www.fotor.com/images2/fea…"}}bash
說明:微信
通知內容擴展過程當中,展現在用戶面前的NotificationViewController的結構說明如圖以下: 網絡
一、設置actions: 從NotificationViewController這個類能夠看出,它直接繼承於ViewController,所以能夠在這個類中重寫相關方法,來修改界面的相關佈局及樣式。在這個界面展開以前,用戶經過UNNotificationAction仍是能夠與相應推送通知交互的,可是***用戶和這個通知內容擴展界面沒法直接交互***。(這些actions有兩種設置途徑:用戶能夠經過在AppDelegate中實例化UIUserNotificationSettings來間接設置這些actions;在UNNotificationServiceExtension中也能夠處理這些actions。)session
二、設置category: 推送通知內容中的category字段,與UNNotificationContentExtension的info.plist中UNNotificationExtensionCategory字段的值要匹配到,系統才能找到自定義的UI。app
在aps字符串中直接設置category字段以下:ide
{ "aps":{ "alert":"Testing...(0)","badge":1,"sound":"default","category":"QiShareCategoryIdentifier"}}
複製代碼
在NotificationService.m中設置category的值以下:
self.bestAttemptContent.categoryIdentifier = @"QiShareCategoryIdentifier";
複製代碼
info.plist中關於category的配置以下:
三、UNNotificationContentExtension協議:NotificationViewController 中生成時默認實現了。
簡單的英文註釋很明瞭:
// 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支持
自定義內容擴展界面示例代碼以下:
#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);
// 設置控件邊框顏色
[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:@"觸發了%@", 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
複製代碼
說明:
工程源碼:GitHub地址
關注咱們的途徑有:
QiShare(簡書)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公衆號)