// // NotificationService.swift // JuickPush // // Created by Vitaly Takmazov on 16.09.2020. // Copyright © 2020 com.juick. All rights reserved. // import Foundation 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; self.bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent if let bestAttemptContent = self.bestAttemptContent { if let avatarURL = URL(string: (request.content.userInfo["avatarUrl"] as? String)!) { let task = URLSession.shared.downloadTask(with: avatarURL) { (location, response, error) in if error == nil { if let suggestedName = response?.suggestedFilename { let temporaryDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(suggestedName) if let currentPath = location?.path { do { try FileManager.default.moveItem(atPath: currentPath, toPath: temporaryDirectory.path) if let avatarAttachment = try? UNNotificationAttachment(identifier: avatarURL.lastPathComponent, url: temporaryDirectory, options: nil) { bestAttemptContent.attachments = [avatarAttachment] self.contentHandler?(bestAttemptContent) } } catch { self.contentHandler?(bestAttemptContent) } } } } } task.resume() } } } override func serviceExtensionTimeWillExpire() { if let bestAttemptContent = bestAttemptContent, let contentHandler = contentHandler { contentHandler(bestAttemptContent) } } }