- 在tmp文件夹中创建目录
- 将的
NSData
表示形式写入UIImage
新创建的目录 - 使用URL到tmp文件夹中的文件创建UNNotificationAttachment
- 清理tmp文件夹
我写了一个扩展
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就可以像这样
let identifier = ProcessInfo.processInfo.globallyUniqueStringlet 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会将图像文件复制到自己的位置。



