ios - 带有 UIImage 或远程 URL 的 UNNotificationAttachment

标签 ios swift uiimage unnotificationserviceextension unnotificationattachment

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

所以我将这个图像作为 UIImage,并且不认为需要将它写入磁盘上我的应用程序目录/组容器中以设置通知。

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

最佳答案

  1. 在tmp文件夹中创建目录
  2. UIImageNSData 表示写入新创建的目录
  3. 创建带有 url 的 UNNotificationAttachment 到 tmp 文件夹中的文件
  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
    }
}

因此,要从 UIImage 创建带有 UNUserNotificationAttachmentUNUserNotificationRequest,您可以像这样简单地做某事

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/

相关文章:

ios - 使用 Azure 总线服务队列在 iOS 设备和后端之间代理消息传输

ios - 如果没有可选关系属性的值,核心数据无法加载?!?迅速

ios - 自定义 UIPanGestureRecognizer 根据触摸开始位置开始?

ios - Swift:有什么方法可以将签名保存到一串点中吗?

ios - 初始化的枚举返回错误的 hashValue

ios - IOS自动抓图

ios - 将格式化测量值限制为 2 位数字

c# - 像 c# 一样的 swift 静态扩展

iphone - 快速从资源和/或文档目录获取图像

ios - 来自 URL 的图像不遵循 Storyboard 中的样式规则