|
| 1 | +// |
| 2 | +// AppDelegate.swift |
| 3 | +// Codive |
| 4 | +// |
| 5 | +// Created by Claude on 4/26/26. |
| 6 | +// |
| 7 | + |
| 8 | +import UIKit |
| 9 | +import FirebaseMessaging |
| 10 | +import UserNotifications |
| 11 | + |
| 12 | +final class AppDelegate: NSObject, UIApplicationDelegate { |
| 13 | + |
| 14 | + /// 앱이 죽어있을 때 푸시 탭으로 실행된 경우 저장해두는 pending 데이터 |
| 15 | + static var pendingPushUserInfo: [AnyHashable: Any]? |
| 16 | + |
| 17 | + func application( |
| 18 | + _ application: UIApplication, |
| 19 | + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil |
| 20 | + ) -> Bool { |
| 21 | + UNUserNotificationCenter.current().delegate = self |
| 22 | + Messaging.messaging().delegate = self |
| 23 | + |
| 24 | + requestNotificationPermission(application) |
| 25 | + |
| 26 | + return true |
| 27 | + } |
| 28 | + |
| 29 | + // MARK: - APNs Token |
| 30 | + |
| 31 | + func application( |
| 32 | + _ application: UIApplication, |
| 33 | + didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data |
| 34 | + ) { |
| 35 | + Messaging.messaging().apnsToken = deviceToken |
| 36 | + } |
| 37 | + |
| 38 | + func application( |
| 39 | + _ application: UIApplication, |
| 40 | + didFailToRegisterForRemoteNotificationsWithError error: Error |
| 41 | + ) { |
| 42 | + #if DEBUG |
| 43 | + print("[Push] APNs 등록 실패: \(error.localizedDescription)") |
| 44 | + #endif |
| 45 | + } |
| 46 | + |
| 47 | + // MARK: - Permission |
| 48 | + |
| 49 | + private func requestNotificationPermission(_ application: UIApplication) { |
| 50 | + let options: UNAuthorizationOptions = [.alert, .badge, .sound] |
| 51 | + UNUserNotificationCenter.current().requestAuthorization(options: options) { granted, error in |
| 52 | + #if DEBUG |
| 53 | + if let error { |
| 54 | + print("[Push] 권한 요청 실패: \(error.localizedDescription)") |
| 55 | + } else { |
| 56 | + print("[Push] 알림 권한 허용: \(granted)") |
| 57 | + } |
| 58 | + #endif |
| 59 | + |
| 60 | + guard granted else { return } |
| 61 | + |
| 62 | + DispatchQueue.main.async { |
| 63 | + application.registerForRemoteNotifications() |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// MARK: - UNUserNotificationCenterDelegate |
| 70 | + |
| 71 | +extension AppDelegate: UNUserNotificationCenterDelegate { |
| 72 | + |
| 73 | + // 포그라운드에서 알림 수신 시 배너 표시 |
| 74 | + func userNotificationCenter( |
| 75 | + _ center: UNUserNotificationCenter, |
| 76 | + willPresent notification: UNNotification, |
| 77 | + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void |
| 78 | + ) { |
| 79 | + completionHandler([.banner, .badge, .sound]) |
| 80 | + } |
| 81 | + |
| 82 | + // 알림 탭 시 처리 |
| 83 | + func userNotificationCenter( |
| 84 | + _ center: UNUserNotificationCenter, |
| 85 | + didReceive response: UNNotificationResponse, |
| 86 | + withCompletionHandler completionHandler: @escaping () -> Void |
| 87 | + ) { |
| 88 | + let userInfo = response.notification.request.content.userInfo |
| 89 | + |
| 90 | + #if DEBUG |
| 91 | + print("[Push] 알림 탭 userInfo: \(userInfo)") |
| 92 | + #endif |
| 93 | + |
| 94 | + // MainTabView가 아직 없으면 pending으로 저장, 있으면 바로 전달 |
| 95 | + AppDelegate.pendingPushUserInfo = userInfo |
| 96 | + |
| 97 | + NotificationCenter.default.post( |
| 98 | + name: .pushNotificationTapped, |
| 99 | + object: nil, |
| 100 | + userInfo: userInfo |
| 101 | + ) |
| 102 | + |
| 103 | + completionHandler() |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +// MARK: - MessagingDelegate |
| 108 | + |
| 109 | +extension AppDelegate: MessagingDelegate { |
| 110 | + |
| 111 | + func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { |
| 112 | + guard let fcmToken else { return } |
| 113 | + |
| 114 | + #if DEBUG |
| 115 | + AppLog.push.debug("FCM 토큰: \(fcmToken.masked(), privacy: .public)") |
| 116 | + #endif |
| 117 | + |
| 118 | + // UserDefaults에 저장 (로그인 후 서버 전송용) |
| 119 | + UserDefaults.standard.set(fcmToken, forKey: "fcmToken") |
| 120 | + |
| 121 | + // 로그인 상태면 서버에 즉시 전송 |
| 122 | + Task { |
| 123 | + await sendFCMTokenToServerIfNeeded(fcmToken) |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + @MainActor |
| 128 | + private func sendFCMTokenToServerIfNeeded(_ fcmToken: String) async { |
| 129 | + let tokenService = TokenService() |
| 130 | + |
| 131 | + guard tokenService.hasValidTokens(), |
| 132 | + !tokenService.isAccessTokenExpired() else { |
| 133 | + return |
| 134 | + } |
| 135 | + |
| 136 | + do { |
| 137 | + let authAPIService = AuthAPIService() |
| 138 | + try await authAPIService.renewDeviceToken(deviceToken: fcmToken) |
| 139 | + #if DEBUG |
| 140 | + print("[Push] 서버에 FCM 토큰 전송 완료") |
| 141 | + #endif |
| 142 | + } catch { |
| 143 | + #if DEBUG |
| 144 | + print("[Push] 서버 FCM 토큰 전송 실패: \(error.localizedDescription)") |
| 145 | + #endif |
| 146 | + } |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +// MARK: - Notification Name |
| 151 | + |
| 152 | +extension Notification.Name { |
| 153 | + static let pushNotificationTapped = Notification.Name("pushNotificationTapped") |
| 154 | +} |
0 commit comments