一尘不染

具有UIImage或远程URL的UNNotificationAttachment

swift

在我的Notification Service Extension我从一个URL下载的图像显示为UNNotificationAttachment一个通知。

因此,我将此图像作为UIImage,没有看到仅在设置通知时将其写入磁盘上的应用程序目录/组容器中的需要。

有没有一种UNNotificationAttachment使用UIImage 创建的好方法? (应适用于本地和远程通知)


阅读 485

收藏
2020-07-07

共1个答案

一尘不染

  1. 在tmp文件夹中创建目录
  2. 将的NSData表示形式写入UIImage新创建的目录
  3. 使用URL到tmp文件夹中的文件创建UNNotificationAttachment
  4. 清理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.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会将图像文件复制到自己的位置。

2020-07-07