Search code examples
iosobjective-cattachmentunnotificationserviceextensionunnotificationattachment

Path to file(image) in Notification Service Extension folder


I am trying to add a local image(icon) as an attachment to a remote notification on iOS 12. In other words the image URL is not passed in the notification userInfo but is determined internally based on other criteria in userInfo. Therefore I want a library of icons bundled with the app to choose from. I can't determine what the relative URL would be if I wanted to add an image of this kind to the notification. This is what I'm trying to do, and the "example.png" file is in the "Notification Service Extension" folder.

I want to know how to copy over a folder of images from xcode to the device I'm building to.

Then I want to know what the relative path would be to access these images to use for the attachments.

UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = @"Title";
content.body = @"Body";
content.sound = [UNNotificationSound defaultSound];
NSURL *imageURL = [NSURL fileURLWithPath:@"example.png"];
NSError *error;
UNNotificationAttachment *icon = [UNNotificationAttachment attachmentWithIdentifier:@"image" URL:imageURL options:nil error:&error];
if (error)
{
    NSLog(@"error while storing image attachment in notification: %@", error);
}
if (icon)
{
    content.attachments = @[icon];
}

Solution

  • Just copy the directory of images to your Xcode project. Xcode will bundle it and copy it to the device. On the device, do the following (taken directly from the docs)

    NSBundle *main = [NSBundle mainBundle];
    NSString *resourcePath = [main pathForResource:@"Seagull" ofType:@"jpg"];
    

    That from the docs, but there is also a URLForResource:withExtention which is better to use.