개발 - iOS SwiftUI

iOS SwiftUI current View 상태 관리 예제

개미v 2023. 11. 5. 12:36

SwiftUI에서 Firebase Message 수신 처리를 하는데, 현재 View가 무엇인지 확인하는 예제 입니다.

 

 

CurrentViewObject.swift
현재 View를 저장할 수 있는 ObservableObject를 선언 합니다.

import Foundation
import SwiftUI

class CurrentViewObject: ObservableObject {
    // 현재 View 저장 변수
    @Published var currentView: (any View)?
    
    func setCurrentView(_ view: AnyView) {
        currentView = view
    }
}

 

metalkApp.swift
메인함수에서 EnvironmentObject를 설정 합니다.
UIApplicationDelegateAdaptor 로 설정해줘야 extension AppDelegate 에서 접근 가능합니다.

import Foundation
import SwiftUI
import Firebase
import FirebaseMessaging

@main
struct metalkApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            IntroView()
                .environmentObject(appDelegate.currentViewObject)
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    
    // 현재 View 저장 객체
    var currentViewObject = CurrentViewObject()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        ...
        return true
    }
}

// FCM 처리
extension AppDelegate : MessagingDelegate, UNUserNotificationCenterDelegate {
    
    // FCM 메세지 수신
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
       
        // 현재 대화 내용 화면인 경우
        if UIApplication.shared.applicationState == .active && type(of: currentViewObject.currentView!) == ChatContentView.self {
            completionHandler([])
        }
        
        // 앱이 실행중이지 않거나, 다른 화면인 경우
        else {
            completionHandler([.banner, .sound, .badge])
        }
    }
}

 

ChatContentView.swift
각 View에서는 현재 View의 상태에 대해서 저장합니다.

import Foundation
import SwiftUI

struct ChatContentView: View {
   
    @EnvironmentObject var currentViewObject: CurrentViewObject

    var body: some View {
        VStack {
        }
        .onAppear() {
            // 현재 View 저장
            currentViewObject.currentView = self
        }
        .task() {
            startTask()
        }
    }
    
    func startTask() {
    }
}