Files
ladill-mini/apps/ios/LadillMini/Push/PushTokenRegistrar.swift
T
isaaccladandCursor ea6afb80a4
Deploy Ladill Mini / deploy (push) Successful in 35s
Add Ladill Mini native Android and iOS apps.
Ship full-featured mobile clients with auth, payments, QRs, push notifications, and iOS polish including Figtree typography, app icons, and QR previews.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-11 22:30:35 +00:00

62 lines
2.1 KiB
Swift

import FirebaseMessaging
import UIKit
import UserNotifications
/// Registers the FCM device token with the Ladill Mini API when the user is signed in.
@MainActor
enum PushTokenRegistrar {
static func requestPermissionAndRegisterForRemoteNotifications() async {
let center = UNUserNotificationCenter.current()
let granted = (try? await center.requestAuthorization(options: [.alert, .badge, .sound])) ?? false
guard granted else { return }
UIApplication.shared.registerForRemoteNotifications()
}
static func registerIfLoggedIn() async {
guard SessionStore.shared.isLoggedIn else { return }
await requestPermissionAndRegisterForRemoteNotifications()
await uploadCurrentTokenIfAvailable()
}
static func onTokenRefresh(_ token: String) async {
guard SessionStore.shared.isLoggedIn else { return }
await upload(token: token)
}
static func unregister() async {
guard let token = await fetchFCMToken() else { return }
try? await APIClient.shared.unregisterPushToken(token: token)
}
private static func uploadCurrentTokenIfAvailable() async {
guard let token = await fetchFCMToken() else { return }
await upload(token: token)
}
private static func upload(token: String) async {
do {
try await APIClient.shared.registerPushToken(PushTokenRequest(token: token))
} catch {
#if DEBUG
print("PushTokenRegistrar: upload failed — \(error.localizedDescription)")
#endif
}
}
private static func fetchFCMToken() async -> String? {
await withCheckedContinuation { continuation in
Messaging.messaging().token { token, error in
if let error {
#if DEBUG
print("PushTokenRegistrar: FCM token fetch failed — \(error.localizedDescription)")
#endif
continuation.resume(returning: nil)
return
}
continuation.resume(returning: token)
}
}
}
}