iOS消息推送添加右侧图片展示

98 阅读1分钟

问题

需求想在推送通知栏右侧显示图片

实现方案

  1. 添加推送扩展Service Extension

参考:docs.jiguang.cn/jpush/clien…

2. 在NotificationService.m中,针对获取到的图片url进行下载然后放入到attachment中:

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    // 读取图片地址,并加载
    NSString *imgUrl = [NSString stringWithFormat:@"%@", self.bestAttemptContent.userInfo[@"aps"][@"imageUrl"]];
    if (imgUrl) {
        NSURL *fileURL = [NSURL URLWithString:imgUrl];
        [self downloadAndSave:fileURL handler:^(NSString *localPath) {
            if (localPath){
                UNNotificationAttachment * attachment = [UNNotificationAttachment attachmentWithIdentifier:@"myAttachment" URL:[NSURL fileURLWithPath:localPath] options:nil error:nil];
                self.bestAttemptContent.attachments = @[attachment];
            }
            self.contentHandler(self.bestAttemptContent);
        }];
    }
    else
    {
        self.contentHandler(self.bestAttemptContent);
    }
}

下载图片方法:

#pragma mark - 私有方法
- (void)downloadAndSave:(NSURL *)fileURL handler:(void (^)(NSString *))handler {
    // 这里需要用系统网络请求来下载图片
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:fileURL completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *localPath = nil;
        if (!error) {
            // 临时文件夹路径,APP没有运行时会自动清除图片,不会占用内存
            NSString *localURL = [NSString stringWithFormat:@"%@/%@", NSTemporaryDirectory(), fileURL.lastPathComponent];
            if ([[NSFileManager defaultManager] moveItemAtPath:location.path toPath:localURL error:nil]) {
                localPath = localURL;
                
            }
        }
        handler(localPath);
        
    }];
    [task resume];
}

3. 在Extension的info.plist中添加App Transport Security Settings:

<plist version="1.0">
<dict>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

    // .....

</dict>

4. 【重点】在推送消息中,添加mutable-content=1,不然没法在didReceiveNotificationRequest中收到回调

{
   “aps” : {
      “category” : “SECRET”,
      “mutable-content” : 1,
      “alert” : {
         “title” : “Secret Message!”,
         “body”  : “(Encrypted)”
     },
   },
}

5. Extension的调试,是选择Extension后,选择run的app应用(参考www.jianshu.com/p/5a394b9c1…

  1. 实现:

参考资料: docs.jiguang.cn/jpush/pract… juejin.cn/post/715308…