-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFCMTokenSyncHandler.swift
More file actions
92 lines (81 loc) · 2.75 KB
/
Copy pathFCMTokenSyncHandler.swift
File metadata and controls
92 lines (81 loc) · 2.75 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
// FCMTokenSyncHandler.swift
// DevLog
//
// Created by opfic on 3/19/26.
//
import Combine
import DevLogCore
import DevLogData
import Foundation
final class FCMTokenSyncHandler {
private let messagingService: PushMessagingService
private let userService: UserService
private let notificationCenter: NotificationCenter
private let logger = Logger(category: "FCMTokenSyncHandler")
private var cancellables = Set<AnyCancellable>()
init(
messagingService: PushMessagingService,
userService: UserService,
notificationCenter: NotificationCenter = .default
) {
self.messagingService = messagingService
self.userService = userService
self.notificationCenter = notificationCenter
notificationCenter.publisher(for: .didRefreshFCMToken)
.compactMap { $0.userInfo?["fcmToken"] as? String }
.sink { [weak self] fcmToken in
self?.syncFCMToken(fcmToken)
}
.store(in: &cancellables)
notificationCenter.publisher(for: .didRequestFCMTokenSync)
.sink { [weak self] _ in
self?.requestFCMTokenSync()
}
.store(in: &cancellables)
notificationCenter.publisher(for: .didReceiveAPNSToken)
.compactMap { $0.userInfo?["deviceToken"] as? Data }
.sink { [weak self] deviceToken in
self?.handleAPNSToken(deviceToken)
}
.store(in: &cancellables)
}
}
private extension FCMTokenSyncHandler {
func requestFCMTokenSync() {
Task { [weak self] in
guard let self else { return }
guard await messagingService.isNotificationAuthorized() else {
return
}
notificationCenter.post(name: .didRequestRemoteNotificationRegistration, object: nil)
syncCurrentFCMToken()
}
}
func handleAPNSToken(_ deviceToken: Data) {
messagingService.setAPNSToken(deviceToken)
syncCurrentFCMToken()
}
func syncCurrentFCMToken() {
Task { [weak self] in
guard let self else { return }
do {
guard let fcmToken = try await messagingService.fetchFCMToken() else {
return
}
try await userService.updateFCMToken(fcmToken)
} catch {
logger.error("Failed to sync current FCM token", error: error)
}
}
}
func syncFCMToken(_ fcmToken: String) {
Task { [weak self] in
do {
try await self?.userService.updateFCMToken(fcmToken)
} catch {
self?.logger.error("Failed to sync refreshed FCM token", error: error)
}
}
}
}