// // NotificationService.swift // NotificationService // // Created by Matias Carulli on 5/7/26. // 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 content = bestAttemptContent, let imageUrlString = request.content.userInfo["imageUrl"] as? String, let imageUrl = URL(string: imageUrlString) else { contentHandler(request.content) return } URLSession.shared.downloadTask(with: imageUrl) { location, _, error in defer { contentHandler(content) } guard let location = location, error == nil else { return } let tmpFile = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent(imageUrl.lastPathComponent) try? FileManager.default.moveItem(at: location, to: tmpFile) if let attachment = try? UNNotificationAttachment(identifier: "avatar", url: tmpFile) { content.attachments = [attachment] } }.resume() } override func serviceExtensionTimeWillExpire() { if let contentHandler = contentHandler, let content = bestAttemptContent { contentHandler(content) } } }