1.2 App Anatomy and Life Cycle

Joohyun·2022년 5월 3일
0

App Life cycle

  • Not running

    • 사용자 또는 시스템에 의해 앱이 시작되지 않거나 종료된 상태
  • Inactive

    • 앱이 foreground에 실행 중이지만, 다른 코드를 수행하는 등의 이유로 터치 이벤트를 받지 않고 있는 상태

    • 주로 다른 상태로 변경될 때 짧게 머무른다.

  • Active

    • 앱이 foreground에 실행 중이고, 터치 이벤트를 받고 있는 상태

    • 특별한 제한 없이 사용자에게 반응한다.

  • Background

    • 앱이 실행 중이지만, 화면에 보이지 않는 상태

    • 사용자가 앱을 종료할 때, suspended 상태가 되기 전 짧게 background에 머문다.

    • 특정 일을 하기 위해 suspended 상태인 앱이 잠시 background 상태가 된다.
      ex) 다운로드, 위치 이벤트, remote notification 등등

    • 해당 상태에서 앱은 가능한 최소한의 일만 해야 한다.

  • Suspended

    • 앱이 메모리상에 존재하지만 코드가 실행되고 있지 않은 상태

    • 시스템은 완수해야 할 일이 없는 background 상태의 앱을 suspended 상태로 일시 중지시킨다.

    • 다른 앱을 위한 공간을 만들기 위해 suspended 상태의 앱을 언제든지 메모리에서 내보낼 수 있다.

AppDelegate

  • AppDelegate class는 앱의 life cycle에 따른 event에 접근을 제공하는 UIApplicationDelegate protocol을 차용한다.

1. Did Finish Launching

  • 앱의 실행이 완료되면 호출

  • 앱이 실행됐을 때, 가장 먼저 수행시킬 코드를 넣을 수 있다.

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

2. Configuration For connecting a Scene Session

  • 새로운 scene이 생성되었을 때 호출

  • Xcode는 기본 scene 환경을 생성하는데에 필요한 정보가 담긴 Info.plist를 해당 method를 통해 프로젝트에 생성한다.

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)
}

3. Did Discard Scene Session

  • 사용자가 iPad에서 앱의 instance를 제거할 때, 해당 scene에 대한 정보와 함께 호출

  • 여러개의 scene session 정보를 가질 수 있다.

    • 사용자가 동시에 여러개의 instance를 버리는 경우
    • sunspended 상태에서 앱이 종료될 경우
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.
}

SceneDelegate

  • SceneDelegate는 앱의 life cycle 동안, UI-level의 component를 다루는 역할을 한다.

  • SceneDelegate의 method들은 앱이 생성하는 모든 scene에서 호출된다.

  • 각각의 method는 모두 event가 발생하는 scene을 가리키는 UIScene instance를 가진다.

1. Will Connect To

  • scene이 session과 연결될 때 호출

  • 추가될 scene을 위해 필요한 준비를 수행할 수 있다.
    ex) local 저장소로부터 데이터 가져옴, 네트워크 연결 실행

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 }
}

2. Scene Did Disconnect

  • scene이 앱에서 제거될 때 호출

  • 제거될 scene에 대한 정보를 저장하거나, 자원을 정리하는 등의 행위를 수행할 수 있다.

  • UIKit

    • 사용자가 앱 변경 창에서 앱을 닫았을 때 scene을 제거
    • 다른 active 상태의 앱을 위해 background 상태의 scene을 제거
  • 사용자가 다른 앱으로 변경할 때 해당 scene이 제거될지 보장할 수 없기때문에, 해당 method에 코드를 입력하는 것은 일반적이지 않다.

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).
}

3. Scene Did Become Active

  • scene이 foreground inactive 상태에서 foreground active 상태로 변경될 때 호출

    • 사용자가 scene을 변경할 때

    • 전화가 오거나, 시스템 알람이 울리는 등 일시적으로 앱이 inactive 상태에 있을 때, 사용자가 '무시'를 선택할 때

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.
}

4. Scene Will Resign Active

  • scene이 foreground active 상태에서 떠날 때 호출

    • 사용자가 scene을 닫거나 앱을 종료할 때

    • 전화가 오거나, 시스템 알람이 울릴 때

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).
}

5. Scene Will Enter Foreground

  • background 상태에서 foreground active 상태로 변경될 때 sceneDidBecomeActive(_:) 이전에 호출

  • scene이 background 상태가 될 때 동작시켰던 것들을 취소할 수 있다.

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.
}

6. Scene Did Enter Background

  • scene이 background 상태에 들어갈 때 sceneWillResignActive(_:) 뒤에 호출

  • 요구하는 프로세스를 모으거나 사용자의 상태를 저장할 수 있다.

App life cycle 예시

  • 앱 실행
    • Application did finish launching
    • Scene will connect to session
    • Scene will enter foreground
    • Scene did become active
  • 앱 실행 중 홈으로 이동
    • Scene will resign active
    • Scene did enter background
  • 앱 선택 창을 통해 다시 앱 실행
    • Scene will enter foreground
    • Scene did become active
  • 앱 실행 중 앱 선택창에 갔다가 돌아옴
    • Scene will resign active
    • Scene did become active

ViewController에서 AppDelegate 접근

var appDelegate = (UIApplication.shared.delegate as! AppDelegate)
  • AppDelegate instance는 singleton (앱 전체에서 하나의 class instance를 공유)

SceneDelegate에서 ViewController 접근

var viewController: ViewController?
viewController = window?.rootViewController as? ViewController
profile
IOS Developer

0개의 댓글