UNNotificationAttachment

UNNotificationAttachment

Notification Service Extension中,我正在从URL下载图像,以在通知中显示为UNNotificationAttachment

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

是否有一个很好的方法用UIImage创建UNNotificationAttachment
(应适用于本地和远程通知)

最佳答案

  • 在tmp文件夹
  • 中创建目录
  • NSDataUIImage表示形式写入新创建的目录
  • 使用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中使用UNUserNotificationAttachment创建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会将图像文件复制到自己的位置。

    关于ios - 具有UIImage或远程URL的UNNotificationAttachment,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39103095/

    10-10 14:21