From 2168b30da2b684b5dac35616e9ea049ae66b4434 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 16 Sep 2020 17:39:47 +0300 Subject: NotificationService rewritten in Swift, added dummy test target --- JuickPush/NotificationService.swift | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 JuickPush/NotificationService.swift (limited to 'JuickPush/NotificationService.swift') diff --git a/JuickPush/NotificationService.swift b/JuickPush/NotificationService.swift new file mode 100644 index 0000000..380d2b0 --- /dev/null +++ b/JuickPush/NotificationService.swift @@ -0,0 +1,48 @@ +// +// 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) + } + } +} -- cgit v1.2.3