App LifeCycle

이미지 출처 : https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle

 

✅ App LifeCycle

Aplle에서 정의하는 앱의 상태는 크게 5가지로 구분된다.

  • Not Running : 앱이 시작되지 않았거나, 실행되었지만 시스템에 의해 종료된 상태
  • Inactive: 앱이 전면에서 실행중이지만, 아무런 이벤트를 받지 않는 상태, 앱의 상태 변화 과정에서 잠깐 머무는 단계
  • Active: 앱이 전면에서 실행중이며, 이벤트를 받고있는 상태
  • Background: 앱이 백그라운드에 있지만, 여전히 코드가 실행되고 있는 상태
  • Suspended: 앱이 메모리에 유지되지만, 실행되는 코드가 없는 상태

앱의 실행 상태가 변화할 때마다 Application 인스턴스는 UIApplicationDelegate 프로토콜에 정의된 특정 메소드를 호출한다.

 

SceneDelegate와 AppDelegate는 Xcode Project를 처음 생성할 때 기본적으로 생성되며,

AppLifeCycle과 관련된 동작들은 SceneDelgate와 AppDelegate에서 이루어진다.

 

그래서 SceneDelegate가 뭐임?

 

SceneDelgate -> UI의 상태를 알 수 있는 UILifeCycle을 관리하는 역할

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
   // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
   // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
   guard let _ = (scene as? UIWindowScene) else { return } 
        
   = 새로운 UIWindow를 생성하여 scene에 연결하고, rootViewController를 설정.
     Storyboard를 사용하면 자동으로 초기화 되며, 그렇지 않을 때는 이곳에서 추가 설정이 필요.
     보통 code로 UI를 짤 때, 첫 view를 만들 때 쓰임.
}

func sceneWillEnterForeground(_ scene: UIScene) {
   // Called as the scene transitions from the background to the foreground.
   // Use this method to undo the changes made on entering the background.
      = scene이 background  foreground(혹은 처음 active)로 전환될 때 호출되는 메소드.
        background상태로 돌입할 때의 변화들을 다시 원상복귀 시키는 작업을 한다.
}

func sceneDidBecomeActive(_ scene: UIScene) {
   // Called when the scene has moved from an inactive state to an active state.
   // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
      = inactive  active상태로 scene이 돌입할 때 호출되는 메소드
        scene이 inactive되면서 멈춰있었던 작업들은 다시 시작하는 작업을 한다.
}

func sceneWillResignActive(_ scene: UIScene) {
   // Called when the scene will move from an active state to an inactive state.
   // This may occur due to temporary interruptions (ex. an incoming phone call).
      = scene이 active  inactive 상태로 빠질 때 호출된다
        추가로, 이러한 전환은 interrupt에 의해 일어날 수 있다(ex) 전화가 왔을 때)
}

func sceneDidEnterBackground(_ scene: UIScene) {
   // Called as the scene transitions from the foreground to the background.
   // Use this method to save data, release shared resources, and store enough scene-specific state information
   // to restore the scene back to its current state.
      = scene이 foreground  background 상태로 돌입할 때 호출된다.
        data를 저장하고, 공유 중이던 자원을 돌려주거나 
        다시 scene이 foreground로 돌입할 때 필요한 data들을 처리하는 작업을 한다.
}

func sceneDidDisconnect(_ scene: UIScene) {
   // Called as the scene is being released by the system.
   // This occurs shortly after the scene enters the background, or when its session is discarded.
   // Release any resources associated with this scene that can be re-created the next time the scene connects.
   // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
      = scene이 폐기되거나 background상태에 들어갈 때 호출되는 메소드.
        scene이 사용하던 자원을 돌려주는 작업을 한다.
        scene은 폐기될 필요가 없다면 다시 연결될 수 있다.(disconnect는 app 종료와는 다른 개념임.)
}

 

AppDelegate

-> 앱의 생명주기 이벤트를 관리하고, 앱의 상태 변화를 처리하며 중요한 시스템 이벤트를 처리한다.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

 

위에 메서드들은 프로젝트 생성시에 기본적으로 구현되어 있는 메서드들이다.

다음으로 소개할 메서드들은 사용자가 필요에 따라 작업을 구현할 수 있는 메서드이고, App LifeCycle과 관련이 있다.

// 앱이 비활성 상태로 전환될 때 호출
    func applicationWillResignActive(_ application: UIApplication) {
        // 일시 중지 코드
    }

    // 앱이 백그라운드로 진입할 때 호출
    func applicationDidEnterBackground(_ application: UIApplication) {
        // 백그라운드 작업
    }

    // 앱이 포그라운드로 전환되기 직전에 호출
    func applicationWillEnterForeground(_ application: UIApplication) {
        // 포그라운드 준비 작업
    }

    // 앱이 활성 상태로 돌아왔을 때 호출
    func applicationDidBecomeActive(_ application: UIApplication) {
        // 활성화 작업
    }

    // 앱이 종료될 때 호출
    func applicationWillTerminate(_ application: UIApplication) {
        // 종료 작업
    }

 


View Controller Life Cycle 메서드 호출 순서

✅ View LifeCycle

 

1. loadView()

 앱이 뷰 컨트롤러의 뷰를 만들 때 호출. 주로 코드로 뷰를 생성할 때 사용한다. (XIB, StoryBoard 사용시, 사용 X)

 

2. viewDidLoad()

 뷰가 메모리에 로드된 후 한 번 호출하고, 여기에서 뷰의 초기설정, 데이터 로딩, 네트워크 요청 등을 설정한다. 모든 서브뷰가 설정되었는지 확인하고 추가 설정.

 

3. viewWillAppear(_:)

 뷰가 화면에 나타나기 직전에 호출하고, 뷰가 보이기 전에 마지막으로 상태를 업데이트하거나, 화면에 나타날 준비를 한다.

 

4. viewWillLayoutSubviews()

 뷰의 서브뷰가 레이아웃되기 직전에 호출하고, 레이아웃이 변경될 때마다 호출되며, 뷰의 크기나 위치를 조정할 수 있다.

 

5. viedwDidLayoutSubviews()

 뷰의 서브뷰가 레이아웃된 후에 호출하고, 모든 레이아웃이 완료된 후 추가 작업을 수행할 수 있다.

 

6. viewDidAppear(_:)

 뷰가 화면에 완전히 나타난 후에 호출하고, 뷰가 화면에 보인 후 애니메이션을 시작하거나 추가적인 작업을 수행 함.

 

7. viewWillDisappear(_:)

 뷰가 화면에서 사라지기 직전에 호출하며, 뷰가 사라지기 전에 상태를 저장하거나 정리작업을 함.

 

8. viewDidDisappear(_:)

 뷰가 화면에서 완전히 사라진 후에 호출하고, 뷰가 보이지 않게 된 후에 필요한 작업을 추가로 한다.

 

 

 

 

 

 

 

 

'Swift' 카테고리의 다른 글

Swift Optional  (0) 2024.06.28
CoW (Copy - on - Write)  (0) 2024.06.27
Swift preview  (0) 2024.06.25
Swift Lint란?  (0) 2024.06.24
NSExpression Class  (0) 2024.06.23