本Demo推送运用的是极光推送(换成其他推送改动也不大)极光文档 极光Demo
先看下效果图,在系统的推送弹窗右侧添加了一个图片
工程配备(一)
- 首先需求一个现已集成了极光推送,并且能够正常接收推送的工程(参考极光文档again);
- 配备主Target,如下截图所示,勾选主Target的Background Modes;
- 创立Service Extension,看下面的三图;
- 给PushExtension(子Target)配备Push Notifications,这一步操作就和主Target的配备推送相同;
工程配备(二)集成JPushExtension
这一步是按照需求可选的,引进JPushExtension的意图是为了极光推送做计算
处理推送闪现的内容
这是配备好的工程目录,多了一个PushExtention
文件夹
NotificationService.m
文件的内容改为如下
#import "NotificationService.h"
#import "JPushNotificationExtensionService.h"
@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@end
@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
// 读取图片地址,并加载
NSString *imgUrl = [NSString stringWithFormat:@"%@", self.bestAttemptContent.userInfo[@"imageUrl"]]; // ⚠️图片字段的key值需求跟后台开发共同
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 apnsDeliverWith:request];
}];
} else {
[self apnsDeliverWith:request];
}
}
- (void)serviceExtensionTimeWillExpire {
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];
}
- (void)apnsDeliverWith:(UNNotificationRequest *)request {
[JPushNotificationExtensionService jpushSetAppkey:@"本应用在极光途径的AppKey"];
[JPushNotificationExtensionService jpushReceiveNotificationRequest:request with:^ {
NSLog(@"apns upload success");
self.contentHandler(self.bestAttemptContent);
}];
}
@end
注意事项
假如传了图片地址却还不闪现,不要惊慌,先请保证图片别太大,并且能够运用NSURLSession下载,否则就会出现图片不闪现的问题。