Swift UI 에서 Appdelegate, Scenedelegate ? [1]

이승원·2022년 11월 21일
0

iOS

목록 보기
2/6
post-thumbnail

지난 포스트에서 App Life Cycle을 Appdelegate 및 SceneDelegate 파일을 통해 공부를 했다.

근데 StoryBoard 가 아닌 SwiftUI로 프로젝트를 만드니깐, 이상하게 저 두파일이 보이지가 않는다. 그래서 구글링을 통해 왜 없는지, 다시 만들 수는 없는지에 대한 정답을 얻었다.

애플에서는 꾸준히 업데이트를 통해 조금 더 사용하기 편한 언어를 만들려고 하는것 같다. 그래서인지 매년 WWDC마다 항상 변경되는 부분이 생기는데, SwiftUI에서도 Appdelegate와 SceneDelegate가 없어지게된 이유는 역시나 편리성이다.

기존에 appdelegate에서는 앱 실행시 최초 1회 실행을 보장하는 경우에, 카카오톡 로그인 초기화하던가, firebase 초기화를 위해서 didFinishLaunchingWithOptions를 사용하고 했다. SceneDelegate에서는 scene이 Active/Inactive 될때, background로 될때 사용할 수 있는 함수들이 있었다.

class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      // 앱 실행시 최초 1회 실행을 보장하는 경우
      // 초기화 등등 을 여기서 실행했었다 
        return true
 }
 
 class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
    func sceneDidBecomeActive(_ scene: UIScene) {
        // Active 상태
    }
    func sceneWillResignActive(_ scene: UIScene) {
        // InActive 상태
    }
    func sceneDidEnterBackground(_ scene: UIScene) {
        // Background 상태
    }
}

이제 그러면 초기화는 하지 말라는건가? 아니다. App 이라는 프로토콜을 통해서 이제는 간편하게 초기화 할 수 있다.

SwiftUI 프로젝트를 처음 생성하면 자동으로 프로젝트 이름app.swift 라는 파일이 생성된다. 파일은 이렇게 작성되어 있다.

import SwiftUI

@main
struct appTestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

현재 코드가 하는 일은 단순히 ContentView()를 앱 실행할때 불러와서 화면에 띄워주는 것이다. 이 파일에서 Appdelegate 및 SceneDelegate의 업무를 모두 다 할 수 있다.

앞서 말한 초기화는 init() 함수로 대체 된다.

import SwiftUI

@main
struct appTestApp: App {

   init() {
        xxxx.configure()
    }
    
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

그러면 SceneDelegate 는 어떻게 변했을까?

import SwiftUI

@main
struct appTestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { (newScenePhase) in
            switch newScenePhase {
            case .active:
                // Active 상태
            case .inactive:
                // InActive 상태
            case .background:
                // background 상태
            @unknown default:
                
            }
        }
    }
}

정말 단순해진것 같다. 아직은 익숙하지 않지만, 이제는 SwiftUI에 맞춰서 사용을 해봐야할 것 같다. 다음 포스트에서는 SwiftUI에서 기존 Appdelegate 및 SceneDelegate를 부활시켜 보자.

profile
개발자 (진)

0개의 댓글