Notification Service Extension實現修改推送內容,添加本地媒體文件

本文會涉及iOS10中的UserNotifications框架,關于UN框架的介紹可以看這里iOS 7 8 9 10本地和推送通知踩坑之旅,適配iOS10之自定義推送通知


iOS10新加了一個Notification Service,那么這個Notification Service又是干什么的呢?
按照蘋果的解釋,Notification Service是一個沒有UI的Extension,用于增加或者替換遠程推送內容的

反映到實際開發上:

  • Notification Service可以解決推送敏感內容的端到端加密(End-to-end encryption
  • 也可以給遠程推送添加本地的媒體文件

流程如下圖所示:


Notification Service.png

新的key: mutable-content


如果需要更改某條推送的內容,則需要在payload中添加mutable-contentkey,讓系統知道這條推送內容可變。

?{
??"aps" : {
????"alert" : "test message available",
????"mutable-content" : 1
???},
??"encrypted-content" : "#myencryptedcontent"
?}

創建Notification Service


創建Notification Service.png

創建好的Notification Servicetarget中有一個繼承自UNNotificationServiceExtensionNotificationService類,該類中包含兩個方法:

  • 方法一:
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler{
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
        
    NSString *newTitle = @"newTitle";
    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", newTitle];
    self.contentHandler(self.bestAttemptContent);
}

當接收到包含mutable-contentkey的payload之后會執行以上方法,同時會給extension一個很短的執行代碼的時間,測試結果大概在30秒左右。

  • 方法二:
- (void)serviceExtensionTimeWillExpire {
    self.contentHandler(self.bestAttemptContent);
}

在Extension被系統殺死之前,會執行上面這個方法,這也是最后一次發出你修改后的通知的機會,如果不做任何操作,則原通知會正常發出。

Notification Service中的End-to-end encryption(端到端加密)


- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler{
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    NSDictionary *userInfo = request.content.userInfo;
    
    NSString *encryptionContent = userInfo[@"encrypted-content"];

    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", encryptionContent];
}

當使用推送傳送一些敏感信息時,可以在上述方法中攔截到推送來的加密數據,然后做解密操作,將推送內容隨之做修改即可。

Notification Service中下載圖片附件并添加顯示


既然iOS10推出了媒體附件富推送,那么我們就可以使用Notification Service擴展來下載媒體附件做一些推送顯示的內容豐富,較好的示例如下:

下載gif示例效果.gif

上圖展示了在Notification Service中下載gif圖并展示的效果,具體的代碼實現在下面:

UNMutableNotificationContent *content = [self.bestAttemptContent mutableCopy];
    
NSURL *imageUrl = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/1159656-22419f571bb4bcd9.JPG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"];
    
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:imageUrl completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        
    NSLog(@"Downloading notification attachment completed with %@", error == nil ? @"success" : [NSString stringWithFormat:@"error: %@", error]);
        
    NSError *fileError;
    // create a local URL with extension
    NSURL *urlWithExtension = [NSURL fileURLWithPath:[location.path stringByAppendingString:imageUrl.lastPathComponent]];
        
    if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:urlWithExtension error:&fileError]) {
        NSLog(@"Could not append  local attachment file name: %@", fileError);
        contentHandler(content);
        return;
    }
        
    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:imageUrl.absoluteString
                                                                                              URL:urlWithExtension options:nil
                                                                                            error:&fileError];
        
    if (!attachment) {
        NSLog(@"Could not create local attachment file: %@", fileError);
        contentHandler(content);
        return;
    }
        
    NSLog(@"Adding attachment: %@", attachment);
        
    NSMutableArray *attachments = content.attachments ? [content.attachments mutableCopy] : [NSMutableArray array];
        
    [attachments addObject:attachment];
        
    content.attachments = attachments;
        
    contentHandler(content);
}];

[task resume];

UNNotificationAttachment的初始化需要傳一個文件的url,而且該url必須是一個file URL,那么我們就需要創建一個路徑,然后把下載好的文件存下來。


具體代碼可以看這里

參考相關問題寫的oc的分類也在上面的鏈接里。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容