我们需要新建两个target如上图所示,也就是我们今天要讲到的NotificationService、NotificationViewController
如上图所示为新建方式
新建完成以后就是如上图所示
二、下面我们来看看上面两个文件里面的应该怎样使用
1:NotificationService的使用
#import "NotificationService.h"
#import "GeTuiExtSdk.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...
NSDictionary *apsDic = [[self dictionaryWithJsonString:self.bestAttemptContent.userInfo[@"payload"] ] objectForKey:@"aps"];
self.bestAttemptContent.title = @"经济日报";
self.bestAttemptContent.subtitle = [apsDic objectForKey:@"pushtopic"];
self.bestAttemptContent.body = [NSString stringWithFormat:@"%@",[[[self.bestAttemptContent.userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"]];
// 附件
NSString *imageUrl = [NSString stringWithFormat:@"%@",[apsDic objectForKey:@"pushimageurl"]];
NSLog(@"userInfo-----%@",self.bestAttemptContent.userInfo);
NSLog(@"alert-----%@",[[self.bestAttemptContent.userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
NSLog(@"apsDic-----%@",apsDic);
// 这里添加一些点击事件,可以在收到通知的时候,添加,也可以在拦截通知的这个扩展中添加
self.bestAttemptContent.categoryIdentifier = @"category2";
if (!imageUrl.length){
self.contentHandler(self.bestAttemptContent);
}
// 图片下载
[self loadAttachmentForUrlString:imageUrl withType:@"jpg" completionHandle:^(UNNotificationAttachment *attach) {
if (attach)
{
self.bestAttemptContent.attachments = [NSArray arrayWithObject:attach];
}
self.contentHandler(self.bestAttemptContent);
// 个推的统计APNs到达情况
[GeTuiExtSdk handelNotificationServiceRequest:request withComplete:^
{
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);
}
// 下载数据
- (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){
}
else{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *localURL = [NSURL fileURLWithPath:[temporaryFileLocation.path stringByAppendingString:fileExt]];
[fileManager moveItemAtURL:temporaryFileLocation toURL:localURL error:&error];
NSError *attachmentError = nil;
attachment = [UNNotificationAttachment attachmentWithIdentifier:@"" URL:localURL options:nil error:&attachmentError];
if (attachmentError)
{
}
}
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];
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
return nil;
}
return dic;
}
1:NotificationViewController的使用
#import
#import
#import
@interface NotificationViewController ()
@property IBOutlet UILabel *label;
@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, copy) void (^completion)(UNNotificationContentExtensionResponseOption option);
@end
@implementation NotificationViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any required interface initialization here.
}
// 按钮的点击事件
- (void)didReceiveNotification:(UNNotification *)notification {
self.label.text = notification.request.content.body;
}
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption option))completion
{
if ([response.actionIdentifier isEqualToString:@"action-open"]){ // 打开
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:@"action-cancel"]){ // 取消、不打开
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
completion(UNNotificationContentExtensionResponseOptionDismissAndForwardAction);
});
}
else if ([response.actionIdentifier isEqualToString:@"action-like"]) {
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"like" ofType:@"m4a"]] error:nil];
[self.player play];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.player stop];
self.player = nil;
completion(UNNotificationContentExtensionResponseOptionDismiss);
});
}
else if ([response.actionIdentifier isEqualToString:@"action-collect"]){
self.label.text = @"收藏成功~";
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:@"action-comment"]){
self.label.text = [(UNTextInputNotificationResponse *)response userText];
}
//这里如果点击的action类型为UNNotificationActionOptionForeground,
//则即使completion设置成Dismiss的,通知也不能消失
}
@end
我们需要注册远程通知
/*
警告:该方法需要开发者自定义,以下代码根据APP支持的iOS系统不同,代码可以对应修改。
以下为演示代码,注意根据实际需要修改,注意测试支持的iOS系统都能获取到DeviceToken
*/
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
// 设置
[self addCustomUICategory];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
}
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}
- (void)addCustomUICategory
{
// --- openAction
UNNotificationAction *openAction = [UNNotificationAction actionWithIdentifier:@"action-open" title:@"查看" options:UNNotificationActionOptionForeground];
//
UNNotificationAction *cancelAction = [UNNotificationAction actionWithIdentifier:@"action-cancel" title:@"不感兴趣" options:UNNotificationActionOptionAuthenticationRequired];
// --- likeAction
// UNNotificationAction *likeAction = [UNNotificationAction actionWithIdentifier:@"action-like" title:@"赞" options:UNNotificationActionOptionAuthenticationRequired];
// // --- collectAction
// UNNotificationAction *collectAction = [UNNotificationAction actionWithIdentifier:@"action-collect" title:@"收藏" options:UNNotificationActionOptionDestructive];
// // --- commentAction
// UNTextInputNotificationAction *commentAction = [UNTextInputNotificationAction actionWithIdentifier:@"action-comment" title:@"评论" options:UNNotificationActionOptionDestructive textInputButtonTitle:@"发送" textInputPlaceholder:@"输入你的评论"];
// --- 组装
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"category2" actions:@[openAction, cancelAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]];
}