Cosa Sono le Rich Push Notifications

Le notifiche push tradizionali contengono solo testo. Con una Notification Service Extension, puoi intercettare il payload della notifica APNs prima che venga mostrata sullo schermo dell'utente, scaricare un'immagine o un video dal server e allegarlo direttamente alla bolla della notifica.

Codice Pratico: NotificationService.swift Extension

import UserNotifications

class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        guard let bestAttemptContent = bestAttemptContent,
              let imageURLString = request.content.userInfo["media_url"] as? String,
              let imageURL = URL(string: imageURLString) else {
            contentHandler(request.content)
            return
        }
        
        // Scarica l'immagine e salvala nel file system temporaneo
        Task {
            do {
                let (tempLocation, _) = try await URLSession.shared.download(from: imageURL)
                let tempDir = FileManager.default.temporaryDirectory
                let localAttachmentURL = tempDir.appendingPathComponent("push_media.jpg")
                
                try? FileManager.default.removeItem(at: localAttachmentURL)
                try FileManager.default.moveItem(at: tempLocation, to: localAttachmentURL)
                
                let attachment = try UNNotificationAttachment(identifier: "media", url: localAttachmentURL, options: nil)
                bestAttemptContent.attachments = [attachment]
                contentHandler(bestAttemptContent)
            } catch {
                contentHandler(bestAttemptContent)
            }
        }
    }
}

Vuoi creare la tua App o hai bisogno di consulenza personalizzata?

Sviluppo app iOS native in SwiftUI, piattaforme backend scalabili e offro supporto strategico per monetizzazione e progetti internazionali.

Diallo Yunus

Diallo Yunus

Indie iOS & macOS Developer, Fondatore di DialloDev e autore di 11+ app pubblicate su Apple App Store. Aiuto startup, creator e aziende a costruire prodotti digitali di successo.