问题
需求想在推送通知栏右侧显示图片
实现方案
-
添加推送扩展Service Extension
参考:https://docs.jiguang.cn/jpush/client/iOS/ios_new_fetures#ios-10-service-extension
- 在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];
}
-
在Extension的info.plist中添加App Transport Security Settings:
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
// .....
</dict>
- 【重点】在推送消息中,添加mutable-content=1,不然没法在didReceiveNotificationRequest中收到回调
{
“aps” : {
“category” : “SECRET”,
“mutable-content” : 1,
“alert” : {
“title” : “Secret Message!”,
“body” : “(Encrypted)”
},
},
}
5.Extension的调试,是选择Extension后,选择run的app应用(参考https://www.jianshu.com/p/5a394b9c1851)
-
实现:
参考资料:
https://docs.jiguang.cn/jpush/practice/set_icon#%E5%8F%B3%E4%BE%A7%E5%9B%BE%E6%A0%87--%E5%A4%A7%E5%9B%BE%E7%89%87
https://juejin.cn/post/7153086261744369677