How to preload resources in Notifications Service extension for Notifications Content extension

277 Views Asked by At

I have quite a simple task. I have implemented a Notifications Service extension along with a Notifications Content extension to implement rich notifications. Now in expanded view (Notifications Content extension) I need to present an image. To make the UX smoother, I want to preload it in Notifications Service extension and then just present it in the Notifications Content extension (which I believe Notifications Service extension are designed for).

Now I know about UNNotificationAttachment and that I can use it to download an image and add it to notification. But an image attachment is presented in short preview of a notification. I need the short preview to stay "clean" and not showing this image.

I know that I can try to use Core Data (SO question), or some other shared storage (UserDefaults). But using this I would have to manage deleting the resource after the notification has been processed. That would mean I would have to somehow find a way to detect when the particular notification has been processed (dismissed/handled), which is not an easy task (e.g., in case the user won't expand short preview but directly dismisses it, I need to delete the resource - how do I detect that?).

Is there some standard way of solving this? Either some temporary storage that gets cleaned by the system as needed? Or is there a way to add a UNNotificationAttachment and configuring it to not show it in the preview? I would prefer the first way, because attachments support only media types, and in general we might need to preload different types of resources (I know this is an edge case, but it can happen).

1

There are 1 best solutions below

0
On

I found a workaround that solves my current problem. If the attachment links a valid image file but uses identifier without the file extension (so no ".png", ".jpg", nor ".gif"), the short preview does not present the preview of the image:

let imageFileIdentifier = "image" // instead of "image.png"
let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)

This probably would not be generic solution, because as documentation says:

If an attached file is corrupted, invalid, or of an unsupported file type, the notification request is not scheduled for delivery.

So I would expect that if the file is not a media file, but e.g., a serialized object in JSON, the notification would not be sent.