我的应用程序中有图像缓存机制。我还需要显示带有图像的本地通知。我有个问题。当我尝试使用图像设置 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
}()
我发现,如果我在 diskUrlString
中添加前缀 file:///private
,那么 URL 会像预期的那样构建。但我仍然不明白,如何在不硬编码此前缀的情况下构建 url。所以现在我可以同时使用缓存和 UNNotificationAttachment
!
关于ios - UNNotificationAttachment 设置图片 URL 到 Caches 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49029846/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |