I create a notification with an image attachment:
let center = UNUserNotificationCenter.current()
center.delegate = self
let content = UNMutableNotificationContent()
// some more stuff…
let paths = NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory = paths[0] as NSString
let fileExtPNG = "#" + "\(imageName)" + " photo.png"
let fileNamePNG = documentsDirectory.appendingPathComponent(fileExtPNG) as String
url = URL(fileURLWithPath: fileNamePNG)
let attachment = try UNNotificationAttachment(identifier: "Image", url: url, options: nil)
content.attachments = [attachment]
I then add the request:
let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: nil)
center.removePendingNotificationRequests(withIdentifiers: [requestIdentifier])
center.add(request) {(error) in }
Problem: when I later test (once notification has been registered), the file do not exist anymore at the url.
I've commented out the add request to confirm.
I have a work around, by creating a temporary copy of the file at the URL and pass it in the attachment.
Then, everything works fine and the copy is deleted.
But that's a bit bizarre. What am I missing here ?
I remember writing this comment in my app a while ago:
// Adding the image to the attachment actually deletes the file (huh?!), so save it with a new name, and use that one instead of the original
I had an image in a folder that I attached to a notification. Then, when I tried to view the original image in the folder, it wasn't there. So, my fix was to make a copy of it (resized and quality lowered as it wasn't necessary to have a full-size image), and attach that file to the notification so my original image wasn't lost.
I think it's expected behaviour, but the Apple docs on attachments
here don't mention it.