iOS10富文字推送--NotificationServiceExtension
阿新 • • 發佈:2018-11-11
新增http協議支援,沒錯,這裡是支援http協議的,不像其他文章說的不支援,配置在另外基礎篇文章裡面有,info.plist檔案裡修改一下就行了
NotificationService檔案
額外添加了一個檔案管理器的欄位,用來儲存資料
@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@property (nonatomic, strong) NSFileManager *fileMgr;
@property (nonatomic, strong) NSURLSessionDownloadTask *download;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSDictionary *userInfo;
@property (nonatomic, strong) NSURL *attchUrl;
@property (nonatomic, strong) NSString *imageExtension;
@end
@implementation NotificationService
LazyLoad
-(NSFileManager *)fileMgr{
return [NSFileManager defaultManager];
}
網路session
-(NSURLSession *)session{
if (_session == nil) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
}
return _session;
}
下載任務
-(NSURLSessionDownloadTask *)download{
if (!_download) {
_download = [self.session downloadTaskWithURL:self.attchUrl completionHandler:^(NSURL * _Nullable tempLocation, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSURL *localURL = [NSURL fileURLWithPath:[tempLocation.path stringByAppendingString:self.imageExtension]];
[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 %@",attachmentError);
}else if (attachment){
self.bestAttemptContent.attachments = @[attachment];
}else{
}
}else{
NSLog(@"downloadTaskerror %@",error.localizedDescription);
}
self.bestAttemptContent.categoryIdentifier = self.userInfo[@"aps"][@"category"];
self.contentHandler(self.bestAttemptContent);
}];
}
return _download;
}
收到遠端通知之後,在當前方法內進行處理,並生成attchment,最終回撥給系統
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
self.resumeTime = 0;
self.userInfo = [request.content.userInfo copy];
NSString * attchUrl = self.userInfo[@"image"];
self.imageExtension = [NSString stringWithFormat:@".%@",[[attchUrl componentsSeparatedByString:@"."] lastObject]];
if (attchUrl) {
self.attchUrl = [NSURL URLWithString:attchUrl];
[self resumeSession];
}
}
開始執行下載多媒體資源任務
- (void)resumeSession{
[self.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