Search code examples
iosswiftunnotificationrequestunnotificationattachment

UNNotificationAttachment set image URL to Caches directory


I have Image cache mechanism in my app. I also need to show local notifications with images. I have a problem. When I try to set UNNotificationAttachment with an image, I get an image from my cache or, if an image doesn't exist, I download it and cache. Then I build a URL to Caches directory, but when I pass this URL to UNNotificationAttachment, I get an error: NSLocalizedDescription=Invalid attachment file URL. What do I make wrong?

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
}()

Solution

  • I have found that if I add a prefix file:///private to diskUrlString, then URL builds like expected. But I didn't still understand, how to build the url without hardcoding this prefix. So now I can use both cache and UNNotificationAttachment!