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地址之後可以實現圖片、音樂和視頻的發送,效果圖如下