Kon*_*nov 13 ios swift ios10 unnotificationattachment
我一直在研究iOS10中引入的丰富通知体验,并坚持将图像作为附件传递给UNNotificationContentExtension.
这是我的ContentExtension:
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet weak var attachmentImage: UIImageView!
func didReceive(_ notification: UNNotification) {
if let attachment = notification.request.content.attachments.first {
if attachment.url.startAccessingSecurityScopedResource() {
attachmentImage.image = UIImage(contentsOfFile: attachment.url.path)
attachment.url.stopAccessingSecurityScopedResource()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
作为教程,我一直在关注WWDC的高级通知视频.我已经检查过 - UIImage我正在分配给UIImageView:
nilCGSize(191x191)/var/mobile/Library/SpringBoard/PushStore/Attachments/<bundle of app>/<...>.png以下是我从应用发送本地通知的方式:
let content = UNMutableNotificationContent()
content.title = "Sample title"
content.body = "Sample body"
content.categoryIdentifier = "myNotificationCategory"
let attachement = try! UNNotificationAttachment(identifier: "image",
url: Bundle.main.url(forResource: "cat", withExtension: "png")!,
options: nil)
content.attachments = [ attachement ]
let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: nil)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(request){(error) in
if (error != nil){
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,通知显示了pic,所以我认为,我正确地发送它,但是在扩展状态(in NotificationViewController)中,我从未成功地显示相同的图像.
我究竟做错了什么?谢谢!
Jef*_*ery 24
使用时创建UIImage时contentsOfFile,UIImage对象仅读取图像标题,指示基本信息,如图像大小等.
因此,尝试移动stopAccessingSecurityScopedResource到[NotificationViewController dealloc].
或使用以下内容:
objective-c代码:
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
Run Code Online (Sandbox Code Playgroud)快速代码:
let imageData = NSData(contentsOf: attachment.url)
let image = UIImage(data: imageData! as Data)
Run Code Online (Sandbox Code Playgroud)没有文件说contentsOfFile只读取图像标题.但是,当我运行以下代码时:
NSString *docFolderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *pngPath = [docFolderPath stringByAppendingPathComponent:@"test.png"];
UIImage *image = [UIImage imageWithContentsOfFile:pngPath];
[[NSFileManager defaultManager] removeItemAtPath:pngPath error:nil];
imageView.image = image;
Run Code Online (Sandbox Code Playgroud)
发生错误:
ImageIO: createDataWithMappedFile:1322: 'open' failed '/Users/fanjie/Library/Developer/CoreSimulator/Devices/FFDFCA06-A75E-4B54-9FC2-8E2AAE3B1405/data/Containers/Data/Application/E2D26210-4A53-424E-9FE8-D522CFD4FD9E/Documents/test.png'
error = 2 (No such file or directory)
Run Code Online (Sandbox Code Playgroud)
所以我得出结论,UIImage contentsOfFile只读取图像标题.
| 归档时间: |
|
| 查看次数: |
6976 次 |
| 最近记录: |