有没有办法在不使用通知服务扩展的情况下将图像附加到推送通知?

时间:2018-03-16 06:45:28

标签: ios objective-c apple-push-notifications ios-targets richpush

我目前正在一个项目中工作,我们已经在应用程序的主要目标中设置了推送通知,现在我们想要添加丰富的推送功能。我在互联网上进行了大量研究,无法在不向项目添加新目标(通知服务扩展)的情况下找到实现丰富推送通知的方法。

正如我在标题中所说,是否可以在不使用此新目标的情况下将图像添加到推送通知中?

1 个答案:

答案 0 :(得分:0)

技术上是,但实际上没有。只要您的图像足够小,以至于对图像的base64编码执行某些操作仍然允许它适合有效负载,您就可以执行此操作。

但是,考虑到添加通知服务扩展程序有多简单,为什么要尝试避免它?您的扩展程序就像这样:

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 {
  }
}

明确指出您需要在此方法中执行同步下载。