UNNotificationAttachment 将图像 URL 设置为缓存目录

UNNotificationAttachment set image URL to Caches directory

我的应用程序中有图像缓存机制。我还需要显示带有图像的本地通知。我有个问题。当我尝试使用图像设置 UNNotificationAttachment 时,我会从缓存中获取图像,或者如果图像不存在,我会下载并缓存。然后我为 Caches 目录构建了一个 URL,但是当我将这个 URL 传递给 UNNotificationAttachment 时,我得到一个错误:NSLocalizedDescription=Invalid attachment file URL。我做错了什么?

if let diskUrlString = UIImageView.sharedImageCache.diskUrlForImageUrl(imageUrl) {
    if let diskUrl = URL(string: diskUrlString) {
       do {
            res = try UNNotificationAttachment(identifier: imageUrlString, url: diskUrl, options: nil)
        } catch (let error) {
            print("error", error)
            // Invalid attachment file URL
        }
    }
}

func diskUrlForImageUrl(_ imageUrl: URL) -> String? {
    let urlRequest = URLRequest(url: imageUrl)
    return ImageCache.cacheDirectory.appending("/\(ImageCache.imageCacheKeyFromURLRequest(urlRequest))")
}

static fileprivate var cacheDirectory: String = { () -> String in
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
    let res = documentsDirectory.appending("/scAvatars")
    let isExist = FileManager.default.fileExists(atPath: res, isDirectory: nil)
    if !isExist {
        try? FileManager.default.createDirectory(atPath: res, withIntermediateDirectories: true, attributes: nil)
    }
    return res
}()

我发现如果我将前缀 file:///private 添加到 diskUrlString,那么 URL 会像预期的那样构建。但我仍然不明白,如何在不硬编码此前缀的情况下构建 url。所以现在我可以同时使用缓存和 UNNotificationAttachment!

这里的问题是您使用的是路径,而不是URL。路径是一个字符串,如“/var/log/foo.log”。 URL 在语义上比路径更复杂。您需要一个描述图像文件在设备文件系统上的位置的 URL。

为图像文件构建一个正确构造的 URL,附件可能会起作用。附件可能还需要类型标识符提示来告诉 iOS 文件中的数据类型。

您不必使用网址。您可以将图像数据与 UNNotificationAttachment.

一起使用

这是示例代码。

let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
            
let imageURL = URL(fileURLWithPath: paths.first!).appendingPathComponent("\(fileName).jpg")
let image = UIImage(contentsOfFile: imageURL.path)
let imageData = image?.pngData()

            
if let unwrappedImageData = imageData, let attachement = try? UNNotificationAttachment(data: unwrappedImageData, options: nil) {
    content.attachments = [attachement]
}