0

I am currently working in a project where we already have the setup for push notifications in our application's main target and now we want to add the rich push functionality. I made a lot of research on the internet and couldn't find a way to implement rich push notifications without adding a new target(Notification Service Extension) to the project.

As I said in title, is it possible to add an image to a push notification without using this new target?

1 Answers1

0

Technically yes, but in reality no. As long as your image is small enough that doing something like a base64 encoding of the image still allows it to fit in the payload, you could do it.

However, considering how simple it is to add a notification service extension, why are you trying to avoid it? Your extension would just look like so:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
  guard let urlPath = request.content.userInfo["media-url"] as? String,
    let url = URL(string: urlPath) else {
      return
  }

  self.contentHandler = contentHandler
  bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent

  defer { contentHandler(bestAttemptContent!) }

  let destination = URL(fileURLWithPath: NSTemporaryDirectory())
      .appendingPathComponent(url.lastPathComponent)

  do {
    let data = try Data(contentsOf: url)
    try data.write(to: destination)

    let attachment = try UNNotificationAttachment(identifier: "",
                                                  url: destination)
    bestAttemptContent!.attachments = [attachment]
  } catch {
  }
}

Notice explicitly that you need to do a synchronous download in this method.

Gargoyle
  • 9,590
  • 16
  • 80
  • 145