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

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地址之后可以实现图片、音乐和视频的发送,效果图如下






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值