swiftui 프로젝트 생성 후 AppDelegate가 없어 당황? 했네요. ㅋㅋㅋ

추가해서 Push 같은 처리를 기존과 같이 가능합니다.

 

@main
struct SwiftUIComponemtApp: App {
	//AppDelegate 설정
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear(perform: {
                    UIApplication.shared.addTapGestureRecognizer()
                })
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    var uuid: String = ""       //디바이스 고유값 (키체인저장)
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        log(direction: .ETC, ofType: self, datas: "didFinishLaunchingWithOptions")
        
        // NotificationCenter 등록
        UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization( //알림,배지,사운드에 대한 권한 요청
            options: authOptions,
            completionHandler: { (granted, error) in
                if granted {
                    log(direction: .ETC, ofType: self, datas: "사용자가 푸시를 허용했습니다.")
                    DispatchQueue.main.async {
                        application.registerForRemoteNotifications()
                    }
                } else {
                    log(direction: .ETC, ofType: self, datas: "사용자가 푸시를 거절했습니다.")
                }
            })
        
        application.applicationIconBadgeNumber = 0
        
        return true
    }
    
    
    // MARK: APNS 디바이스 토큰
    // deviceToken 등록 성공시 실행되는 메서드
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        /*
         ** 시뮬레이터는 디바이스토큰 사용불가. 물리디바이스 확인 필요
         */
        let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
        log(direction: .RECEIVE, ofType: self, datas: "Device Token - \(deviceTokenString)")
        // 토큰값 처리
    }
    
    // deviceToken 등록 실패시 실행되는 메서드
    internal func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        log(direction: .RECEIVE, ofType: self, datas: "Device Token 등록 실패 - \(error.localizedDescription)")
    }
}

// MARK: UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    //실행되고 있는 상태에서 PUSH 클릭시 (백그라운드 -> 포그라운드)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        log(direction: .OBSERVER, ofType: self, datas: "\(userInfo)")
        
        completionHandler()
    }
    
    //PUSH 포그라운드 상태에서 호출
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        
        log(direction: .OBSERVER, ofType: self, datas: "\(userInfo)")
//        completionHandler([]) //포그라운드 상태에서 알림 안받으려면
//        completionHandler([.alert, .badge, .sound])
        completionHandler([.banner,.badge,.list])
    }
}

+ Recent posts