-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathNotificationService.swift
More file actions
69 lines (57 loc) · 2.97 KB
/
Copy pathNotificationService.swift
File metadata and controls
69 lines (57 loc) · 2.97 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// NotificationService.swift
// MindboxNotificationServiceExtension
//
// Created by Dmitry Erofeev on 24.04.2024.
//
import UserNotifications
import MindboxNotifications
class NotificationService: UNNotificationServiceExtension {
static let suiteName = "group.cloud.Mindbox.mindbox.Flutter.Example"
lazy var mindboxService = MindboxNotificationService()
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
saveNotification(request: request)
mindboxService.didReceive(request, withContentHandler: contentHandler)
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
mindboxService.serviceExtensionTimeWillExpire()
}
// We use UserDefaults to save push data for example purposes only. Don't use this solution for yourself
func saveNotification(request: UNNotificationRequest) {
guard let pushData = mindboxService.getMindboxPushData(userInfo: request.content.userInfo) else {
print("Failed to get Mindbox push data")
return
}
let mindboxRemoteMessage = MindboxRemoteMessage(
uniqueKey: pushData.uniqueKey ?? UUID().uuidString,
title: pushData.aps?.alert?.title ?? "",
description: pushData.aps?.alert?.body ?? "",
pushLink: pushData.clickUrl,
imageUrl: pushData.imageUrl,
pushActions: pushData.buttons?.map { PushAction(uniqueKey: $0.uniqueKey ?? UUID().uuidString, text: $0.text ?? "", url: $0.url ?? "") } ?? [],
payload: pushData.payload
)
let userDefaults = UserDefaults(suiteName: NotificationService.suiteName)
let notificationsJson = userDefaults?.string(forKey: "notifications") ?? "[]"
do {
var notifications = try JSONDecoder().decode([String].self, from: Data(notificationsJson.utf8))
let jsonData = try JSONEncoder().encode(mindboxRemoteMessage)
if let jsonString = String(data: jsonData, encoding: .utf8) {
notifications.append(jsonString)
} else {
print("Failed to encode mindboxRemoteMessage to String")
}
let updatedNotificationsData = try JSONEncoder().encode(notifications)
if let updatedNotificationsString = String(data: updatedNotificationsData, encoding: .utf8) {
userDefaults?.set(updatedNotificationsString, forKey: "notifications")
} else {
print("Failed to encode updated notifications to String")
}
} catch {
print("Error processing notifications: \(error)")
}
userDefaults?.synchronize()
}
}