欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS10富文本推送--NotificationServiceExtension

程序员文章站 2022-04-24 08:58:19
NotificationService文件 额外添加了一个文件管理器的字段,用来存储数据 @interface NotificationService () @pro...

NotificationService文件

额外添加了一个文件管理器的字段,用来存储数据

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@property (nonatomic, strong) NSFileManager *fileMgr;
@end
@implementation NotificationService

LazyLoad

-(NSFileManager *)fileMgr{
    return [NSFileManager defaultManager];
}

收到远程通知之后,在当前方法内进行处理,并生成attchment,最终回调给系统

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    NSDictionary * userInfo = request.content.userInfo;
    NSString * attchUrl = userInfo[@"aps"][@"image"];
    NSString *exetension = [NSString stringWithFormat:@".%@",[[attchUrl componentsSeparatedByString:@"."] lastObject]];
    if (attchUrl) {
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSURL *url = [NSURL URLWithString:attchUrl];
        NSURLSessionDownloadTask *download = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable tempLocation, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!error) {
                NSURL *localURL = [NSURL fileURLWithPath:[tempLocation.path stringByAppendingString:exetension]];
                [self.fileMgr moveItemAtURL:tempLocation toURL:localURL error:&error];
                NSError *attachmentError = nil;
                UNNotificationAttachment * attachment = [UNNotificationAttachment attachmentWithIdentifier:@"photo" URL:localURL options:nil error:&attachmentError];
                if (attachmentError) {
                    NSLog(@"%@",attachmentError);
                }else if (attachment){
                    self.bestAttemptContent.attachments = @[attachment];
                }
            }else{
                NSLog(@"%@",error.localizedDescription);
            }
            self.bestAttemptContent.categoryIdentifier = userInfo[@"aps"][@"category"];//这里设置这个类别的标识符
            self.contentHandler(self.bestAttemptContent);//回调给系统 
        }];
        [download resume];
    }
}

超时,异常时调用

- (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