Search code examples
iosswiftcore-dataunnotificationattachmentusernotificationsui

get the URL for NSData saved in CoreData


I'm saving a UIImage to Core Data. So first, I convert it to NSData, then save it.

I need to get the URL for the image after it's saved. I'm doing this because I want to schedule a local notification with an attachment, and the only way to do it, AFAIK, is to with a URL.

Here is my code:

//my image:  
var myImage: UIImage?
var imageData: NSData?
    if let image = myImage {
    imageData = UIImageJPEGRepresentation(image, 0.5)! as NSData
}
myEntity.setValue(imageData, forKey: "image")

And that's how I should add an attachment to the notification:
UNNotificationAttachment.init(identifier: String, url: URL>, options: [AnyHashable : Any]?)

I'm saving the image and scheduling the notification manually when the user taps on a button to save the image.

Please let me know if you need extra info.


Solution

  • You can't get the URL. If you configured this property to use external storage then yes, technically there could be a file URL. Maybe. But there's no documented way to get it, and anyway it might not exist after all-- because the external storage setting doesn't require Core Data to use external storage, it just allows it to do so.

    If you didn't use that setting then there's never any URL since the image is saved as part of the SQLIte file.

    If you need a file URL for the image, save the image to a file separately from Core Data and save the file name as an entity property. Then the file URL is wherever you saved the file.