
上图是我用的格式,"aps"内部的内容ios会自动获取归类.
alert是通知的文字内容,
sound是通知声音,在这取默认,
badge是否显示程序徽章,
重点是mutable-content,这个字段决定了调用自定义通知界面,也就是Notification Content控制器
category是和后台商量好的一个值,显示action,也就是通知下面的按钮,可以扩展一些操作而不必进入程序.
"aps"外部就可以添加一些需要的字段,这就看具体需求了.
推送工具方面的准备工作就已经完成了,下面开始代码干货.
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
NSString * attchUrl = [request.content.userInfo objectForKey:@"image"];
//下载图片,放到本地
UIImage * imageFromUrl = [self getImageFromURL:attchUrl];
//获取documents目录
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectoryPath = [paths objectAtIndex:0];
NSString * localPath = [self saveImage:imageFromUrl withFileName:@"MyImage" ofType:@"png" inDirectory:documentsDirectoryPath];
if (localPath && ![localPath isEqualToString:@""]) {
UNNotificationAttachment * attachment = [UNNotificationAttachment attachmentWithIdentifier:@"photo" URL:[NSURL URLWithString:[@"file://" stringByAppendingString:localPath]] options:nil error:nil];
if (attachment) {
self.bestAttemptContent.attachments = @[attachment];
}
}
self.contentHandler(self.bestAttemptContent);
}
因为不能方便的使用SDImage框架,所以网络请求只能自己松手,丰衣足食,另外,ios10通知虽然可以加载图片,但是只能加载本地的图片,所以这里需要做一个处理,先把图片请求下来,再存到本地
- (UIImage *) getImageFromURL:(NSString *)fileURL {
NSLog(@"执行图片下载函数");
UIImage * result;
//dataWithContentsOfURL方法需要https连接
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];
return result;
}
//将所下载的图片保存到本地
-(NSString *) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
NSString *urlStr = @"";
if ([[extension lowercaseString] isEqualToString:@"png"])
{
urlStr = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]];
[UIImagePNGRepresentation(image) writeToFile:urlStr options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:@"jpg"] ||
[[extension lowercaseString] isEqualToString:@"jpeg"])
{
urlStr = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]];
[UIImageJPEGRepresentation(image, 1.0) writeToFile:urlStr options:NSAtomicWrite error:nil];
} else
{
NSLog(@"extension error");
}
return urlStr;
}










