summaryrefslogtreecommitdiff
path: root/JuickPush/NotificationService.swift
blob: 380d2b03181d6aa44e1d44b2676bb7e8c79191f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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)
        }
    }
}