在我的Notification Service Extension我从一个URL下载的图像显示为UNNotificationAttachment一个通知。
Notification Service Extension
UNNotificationAttachment
因此,我将此图像作为UIImage,没有看到仅在设置通知时将其写入磁盘上的应用程序目录/组容器中的需要。
有没有一种UNNotificationAttachment使用UIImage 创建的好方法? (应适用于本地和远程通知)
NSData
UIImage
我写了一个扩展 UINotificationAttachment
UINotificationAttachment
extension UNNotificationAttachment { static func create(identifier: String, image: UIImage, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? { let fileManager = FileManager.default let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true) do { try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil) let imageFileIdentifier = identifier+".png" let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier) let imageData = UIImage.pngData(image) try imageData()?.write(to: fileURL) let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL, options: options) return imageAttachment } catch { print("error " + error.localizedDescription) } return nil } }
因此,UNUserNotificationRequest使用UNUserNotificationAttachmenta 进行创建UIImage就可以像这样
UNUserNotificationRequest
UNUserNotificationAttachment
let identifier = ProcessInfo.processInfo.globallyUniqueString let content = UNMutableNotificationContent() content.title = "Hello" content.body = "World" if let attachment = UNNotificationAttachment.create(identifier: identifier, image: myImage, options: nil) { // where myImage is any UIImage content.attachments = [attachment] } let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120.0, repeats: false) let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { (error) in // handle error }
这应该可行,因为UNNotificationAttachment会将图像文件复制到自己的位置。