2

I'm trying to send a local notification after some time (e.g. 10 seconds). I want to add an image to the notification from xcassets but the imageURL is always nil.

I've tried creating a Path and then a URL from that path. I've also tried creating a url with the forResource argument = nil so that it finds ANY image with "png" as the extension and still - nil.

    let content = UNMutableNotificationContent()
    content.title = "Notification title"
    content.subtitle = "notification subtitle"
    content.body = "notification body"
    let imageName = "delete"
    guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else {return}
    let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
    content.attachments = [attachment]
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
    let request = UNNotificationRequest(identifier: "notification.id.01", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

I've added print statements to see what happens and I have confirmed that my method returns at the guard statement.

matt
  • 515,959
  • 87
  • 875
  • 1,141
user845978
  • 217
  • 4
  • 10
  • Look inside the .app of your built app. Is there a `delete.png` in the top level? If not then that is why you get `nil` for `imageURL`. – rmaddy Apr 10 '19 at 01:58
  • 1
    You may find this useful: [Is There A Better Way To Use An Image From Assets.xcassets In A Notification Attachment Than This?](https://stackoverflow.com/questions/51488589/is-there-a-better-way-to-use-an-image-from-assets-xcassets-in-a-notification-att) – rmaddy Apr 10 '19 at 02:06

2 Answers2

8

An image can be in one of two places: the asset catalog, or the bundle.

When you say

guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else {return}

you are looking for image in the bundle.

But you have told us yourself, that is not where the image is! It is in the asset catalog.

That is why looking for it in the bundle fails. It isn’t there.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • How would I create an URL with an image that is in xcassets? – user845978 Apr 10 '19 at 04:00
  • 1
    You wouldn’t. If you need to pass a URL you keep the image in the bundle. Or you could pull it out of the asset catalog and save it on disk and pass that URL. – matt Apr 10 '19 at 04:10
0

Adding to Top of Matt's answer, image attachments to UNNotification cannot be directly taken from xcassets. If you want to add any attachment to it, it has to be converted as file URL first.

Please see this post for more details: UNNotificationAttachment with UIImage or Remote URL

Anand
  • 1,820
  • 2
  • 18
  • 25