import SwiftUI import BinaryCodable @main struct FlurSchnapsApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } class AppDelegate: NSObject, UIApplicationDelegate { @AppStorage("deviceToken") var pushToken: Data? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self UIApplication.shared.registerForRemoteNotifications() return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = deviceToken.hexEncoded print("Registered for remote notifications with token: \(token)") uploadNewDeviceToken(deviceToken) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { print(userInfo) completionHandler(UIBackgroundFetchResult.newData) } private func uploadNewDeviceToken(_ token: Data) { if token == pushToken { // Device token unchanged return } Task { let tokenUpload = TokenUpload(currentToken: token, previousToken: pushToken) let data: Data do { data = try BinaryEncoder().encode(tokenUpload) } catch { print("Failed to encode token upload") return } let result: URLResponse do { var request = URLRequest(url: URL(string: "https://christophhagen.de/schnaps/token")!) request.httpMethod = "POST" (_, result) = try await URLSession.shared.upload(for: request, from: data) } catch { print("Failed to upload token: \(error)") return } guard let response = result as? HTTPURLResponse else { print("Invalid response \(result)") return } guard response.statusCode == 200 else { print("Invalid response to token upload: \(response.statusCode)") return } print("Push token uploaded") DispatchQueue.main.async { self.pushToken = token } } // Upload new token, possibly with old one } } extension AppDelegate: UNUserNotificationCenterDelegate { // Receive displayed notifications for iOS 10 devices. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo print(userInfo) // Change this to your preferred presentation option completionHandler([[.banner, .badge, .sound]]) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo print(userInfo) completionHandler() } }