在我的 Notification Service Extension
中,我从 URL 下载图像以在通知中显示为 UNNotificationAttachment
。
所以我将这个图像作为 UIImage,并且不认为需要将它写入磁盘上我的应用程序目录/组容器中以设置通知。
是否有创建带有 UIImage 的 UNNotificationAttachment
的好方法?
(应该适用于本地和远程通知)
最佳答案
- 在tmp文件夹中创建目录
- 将
UIImage
的NSData
表示写入新创建的目录 - 创建带有 url 的 UNNotificationAttachment 到 tmp 文件夹中的文件
- 清理 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
创建带有 UNUserNotificationAttachment
的 UNUserNotificationRequest
,您可以像这样简单地做某事
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/