Как вы можете добавить пользовательское изображение к уведомлению в iOS с реактивной базой - PullRequest
1 голос
/ 14 июня 2019

Я хочу использовать данные в облачных сообщениях Firebase для представления изображения в уведомлении. Изображение указывается в качестве URL-адреса веб-сайта, на котором оно размещено.

Похоже, я хочу добавить изображение в качестве вложения, см. Строку 8 ниже. Однако изображение отсутствует, кроме значка приложения.

const notification = new firebase.notifications.Notification()
        .setNotificationId("notification_id")
        .setTitle(notification.data.title)
        .setBody(notification.data.body)
        .setData({ url: notification.data.url })
        .ios.setLaunchImage(notification.data.icon)
        .android.setBigPicture(notification.data.icon)
        .ios.addAttachment("some_id", notification.data.icon, {});

Проблема в том, что нет сообщений об ошибках, которые могут мне помочь. Уведомление отображается с заголовком и телом, как и ожидалось, но изображение отсутствует. Из того, что я могу прочитать из документации, возможно то, что я хочу сделать.

1 Ответ

0 голосов
/ 17 июня 2019

Короткий ответ: на iOS не поддерживает «расширенные push-уведомления», то есть уведомления с изображениями.

Более длинный ответ заключается в том, что довольно просто добавить поддержку изображения в реактивный проект, если вы добавите небольшой быстрый код.

Работа вокруг:

Откройте ваш проект xcode и перейдите в «редактор» -> «Добавить цель ...». Выберите «Расширение приложения» с именем «Расширение службы уведомлений».

Вы можете назвать его как угодно, но убедитесь, что выбран правильный проект, если вы используете CocoaPods.

После создания замените содержимое override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) на:

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

      // get the variables that is needed later.
      guard let bestAttemptContent = bestAttemptContent,
        let attachmentURLAsString = bestAttemptContent.userInfo["icon"] as? String, 
      // "icon" is the key for the image url in the notification. It 
      // could be named whatever you want.
        let attachmentURL = URL(string: attachmentURLAsString) else {
          return
      }

      // call a custom function to download the image before attaching
      // it to the notification and presenting it.
      downloadImageFrom(url: attachmentURL) { (attachment) in
        if let attachment = attachment {
          bestAttemptContent.attachments = [attachment]
          contentHandler(bestAttemptContent)
        }

      }

Затем необходимо создать функцию downloadImageFrom:

  private func downloadImageFrom(url: URL, with completionHandler: @escaping (UNNotificationAttachment?) -> Void) {
    let task = URLSession.shared.downloadTask(with: url) { (downloadedUrl, response, error) in

      //verify that a url exists.
      guard let downloadedUrl = downloadedUrl else {
        completionHandler(nil)
        return
      }

      // create a local unique filepath.
      var urlPath = URL(fileURLWithPath: NSTemporaryDirectory())
      let uniqueURLEnding = ProcessInfo.processInfo.globallyUniqueString + ".png"
      urlPath = urlPath.appendingPathComponent(uniqueURLEnding)

      // fetch the image from the url
      try? FileManager.default.moveItem(at: downloadedUrl, to: urlPath)

      // if successful, return the image as an attachment.
      do {
        let attachment = try UNNotificationAttachment(identifier: "picture", url: urlPath, options: nil)
        completionHandler(attachment)
      } catch {
        completionHandler(nil)
      }
    }
    task.resume()
  }

При создании приложения оно будет использовать этот код для загрузки уведомлений.

При отправке уведомления вы должны помнить, чтобы включить значение «значок». Пример того, что нужно для отправки уведомления:

    "notification": {
        "body": "body",
        "title": "title"
        "mutable_content": true // this row is required for the notification to work!
    },
    "data": {
        "icon":"https://pusher.com/static_logos/320x320.png", // change to your image url.
    },
...