您的位置:首页 > 移动开发 > IOS开发

iOS10通知(五)--本地实现多媒体通知

2017-03-31 16:52 489 查看
iOS 10 中,开发者现在可以在通知中嵌入图片、音乐或者视频。

为本地通知添加多媒体内容十分简单,只需要通过文件的NSURL创建一个 UNNotificationAttachment 对象,然后将这个对象放到数组中赋值给 content 的 attachments 属性就行了

如果需要实现远程的多媒体通知,那就要用到下篇中的通知拓展,具体操作在下篇介绍,本片只介绍本地多媒体通知

多媒体通知附件的文件大小限制



1、本地多媒体通知的关键代码段实现

-(void)btnClicked
{
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc]init];
content.title = @"多媒体通知";
content.body = @"显示一个图片";

//需要显示多个图片就需要用到后面介绍的自定义的UI

NSString *imageUrlStr = @"http://172.20.90.117/www2/img/r8.jpg";

[self downloadAndSave:[[NSURL alloc] initWithString:imageUrlStr] handler:^(NSURL *localUrl) {

UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"attachment" URL:localUrl options:nil error:nil];

content.attachments = @[attachment];

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
NSString *identifier = @"media";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
//
}];
}];
}

-(void)downloadAndSave:(NSURL *)url handler: (void (^)(NSURL *localUrl)) handler
{
NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// location是沙盒中临时目录下的一个url,文件下载后会存到这个位置,
//由于临时目录中的文件随时可能被删除,建议自己把下载的文件挪到需要的地方
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
handler([NSURL fileURLWithPath:path]);
}];
[task resume];
}


2、更换url地址之后可以实现图片、音乐和视频的发送,效果图如下







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: