iOS10之后的通知具有通知扩展功能,可以在系统受到通知、展示通知时做一些事情。
1. 创建一个UNNotificationServiceExtension和UNNotificationContentExtension:
注意:
(1)如上图默认情况下,两个新生成target的bundleId是主工程名字的bundleId.target名称,不需要修改;
(2)target支持的系统版本号为10及以上。
2. 通知服务扩展UNNotificationServiceExtension
在NotificationService.m文件中,有两个自动生成的方法:
// 系统接到通知后,有最多30秒在这里重写通知内容(如下载附件并更新通知)
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler;
// 处理过程超时,则收到的通知直接展示出来
- (void)serviceExtensionTimeWillExpire;
代码示例如下:
//
// NotificationService.m
// QiNotificationService
//
// Created by wangdacheng on 2018/9/29.
// Copyright © 2018年 dac. All rights reserved.
//
#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";
}
if ([type isEqualToString:@"video"]) {
ext = @"mp4";
}
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":"https://www.fotor.com/images2/features/photo_effects/e_bw.jpg"}}
说明:
(1)加载并处理附件的时间要在30秒之内,才会达到预期效果;
(2)UNNotificationAttachment的url参数接收的是本地文件的url;
(3)服务端在处理推送内容时,需要加上文件类型字段;
(4)aps字符串中的mutable-content字段需要设置为1;
(5)在对NotificationService这个target打断点debug的时候,需要在XCode顶栏选择编译运行的target为NotificationService,否则无法进行实时debug。
3. 通知内容扩展UNNotificationContentExtension
通知内容扩展过程中,展示在用户面前的NotificationViewController的结构说明如图:
(1)设置actions:从NotificationViewController这个类可以看出,它直接继承于ViewController,因此可以在这个类中重写相关方法,来修改界面的相关布局及样式。在这个界面展开之前,用户通过UNNotificationAction还是可以与相应推送通知交互的,但是用户和这个通知内容扩展界面无法直接交互。(这些actions有两种设置途径:用户可以通过在AppDelegate中实例化UIUserNotificationSettings来间接设置这些actions;在UNNotificationServiceExtension中也可以处理这些actions。)
(2)设置category:推送通知内容中的category字段,与UNNotificationContentExtension的info.plist中UNNotificationExtensionCategory字段的值要匹配到,系统才能找到自定义的UI。在aps字符串中直接设置category字段如下:
{ "aps":{ "alert":"Testing...(0)","badge":1,"sound":"default","category":"QiShareCategoryIdentifier"}}
在NotificationService.m中设置category的值:
self.bestAttemptContent.categoryIdentifier = @"QiShareCategoryIdentifier";
info.plist中关于category的配置:
(3)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;
(4)UNNotificationAttachment:attachment支持音频5M(kUTTypeWaveformAudio/kUTTypeMP3/kUTTypeMPEG4Audio/kUTTypeAudioInterchangeFileFormat),图片10M(kUTTypeJPEG/kUTTypeGIF/kUTTypePNG),视频50M(kUTTypeMPEG/kUTTypeMPEG2Video/kUTTypeMPEG4/kUTTypeAVIMovie)
自定义内容扩展界面示例代码如下:
//
// NotificationViewController.m
// NotificationContent
//
// Created by wangdacheng on 2018/9/29.
// Copyright © 2018年 dac. All rights reserved.
//
#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
说明:
(1)宿主工程、服务扩展target和内容扩展target三者中支持的系统版本号要一致。
(2)自定义视图的大小可以通过设置NotificationViewController的preferredContentSize大小来控制,但是用户体验稍显突兀,可以通过设置info.plist中的UNNotificationExtensionInitialContentSizeRatio属性的值来优化;
(3)contentExtension中的info.plist中NSExtension下的NSExtensionAttributes字段下可以配置以下属性的值,UNNotificationExtensionCategory:表示自定义内容假面可以识别的category,可以为数组,即可以为这个content绑定多个通知;UNNotificationExtensionInitialContentSizeRatio:默认的UI界面的高宽比;UNNotificationExtensionDefaultContentHidden:是否显示系统默认的标题栏和内容,可选参数;UNNotificationExtensionOverridesDefaultTitle:是否让系统采用消息的标题作为通知的标题,可选参数。
(4)处理通知内容扩展的过程中关于identifier的设置共有五处(UNNotificationAction、UNNotificationCategory、bestAttemptContent、contentExtension中的info.plist中,aps字符串中),请区别不同identifier的作用。
(5)两个扩展联合使用,在XCode中选择当前target,才能打断点看到相应log信息。