Sobes.tech
Junior — Middle

Ako implementovať odosielanie push notifikácií, ktoré obsahujú obrázok?

sobes.tech AI

Odpoveď od AI

Na odosielanie push notifikácií s obrázkom na iOS sa používa rozšírenie Notification Service Extension. Toto umožňuje zachytiť prichádzajúcu notifikáciu, stiahnuť obrázok z URL a pridať ho do obsahu notifikácie.

Hlavné kroky:

  1. Vytvorte v projekte Notification Service Extension.
  2. V metóde didReceive(_:withContentHandler:) rozšírenie stiahne obrázok z URL uvedeného v payloade notifikácie.
  3. Vytvorte UNNotificationAttachment s načítaným obrázkom.
  4. Pridajte attachment k notifikácii a zavolajte contentHandler.

Príklad kódu v Notification Service Extension:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    self.contentHandler = contentHandler
    bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

    guard let bestAttemptContent = bestAttemptContent,
          let urlString = bestAttemptContent.userInfo["image-url"] as? String,
          let url = URL(string: urlString) else {
        contentHandler(request.content)
        return
    }

    URLSession.shared.downloadTask(with: url) { (location, response, error) in
        if let location = location {
            let tmpDir = FileManager.default.temporaryDirectory
            let tmpFile = tmpDir.appendingPathComponent(url.lastPathComponent)
            try? FileManager.default.moveItem(at: location, to: tmpFile)

            if let attachment = try? UNNotificationAttachment(identifier: "image", url: tmpFile, options: nil) {
                bestAttemptContent.attachments = [attachment]
            }
        }
        contentHandler(bestAttemptContent)
    }.resume()
}

V payload-u push notifikácie je potrebné pridať kľúč s URL obrázka, napríklad:

{
  "aps": {
    "alert": "Nové oznámenie s obrázkom"
  },
  "image-url": "https://example.com/image.jpg"
}