AppDelegate & SceneDelegate ✏️

2022. 9. 27. 16:57UniversityMakeUsChallenge/UMCiOS

 

 

 

 

 

1. AppDelegate

 

https://dev200ok.blogspot.com/2020/05/ios-appdelegate.html

https://developer.apple.com/documentation/uikit/uiapplicationdelegate

 

Apple Developer Documentation

 

developer.apple.com

 

@MainActor protocol UIApplicationDelegate

 

 

Your app delegate object manages your app’s shared behaviors. The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system. Like the UIApplication object, UIKit creates your app delegate object early in your app’s launch cycle so it’s always present. 

Use your app delegate object to handle the following tasks:

  • Initializing your app’s central data structures
    • 앱의 주요 데이터 구조 초기화
  • Configuring your app’s scenes
    • 앱의 Scene들을 구성 (설정함)
  • Responding to notifications originating from outside the app, such as low-memory warnings, download completion notifications, and more
    • 어플 외부의 알림들에 대응 (배터리 부족 경고, 다운로드 완료 알림 등등)
  • Responding to events that target the app itself, and aren’t specific to your app’s scenes, views, or view controllers
    • 어플의 Scene, 뷰 또는 뷰 컨트롤러에 특정하지 않고, 어플에 대한 처리에 대응한다. 
  • Registering for any required services at launch time, such as Apple Push Notification service
    • 실행 시간에 요청되는 사항들을 등록한다. (Apple 알림 기능 등등)

For more information about how you use the app delegate object to initialize your app at launch time, see Responding to the launch of your app.

 

 

Life-cycle management in iOS 12 and earlier

In iOS 12 and earlier, you use your app delegate to manage major life cycle events in your app. Specifically, you use methods of the app delegate to update the state of your app when it enters the foreground or moves to the background. (이후 SceneDelegate가 추가되었다.)

  • For information on what to do when your app enters the foreground, see Preparing your UI to run in the foreground.
  • For information on what to do when your app enters the background, see Preparing your UI to run in the background. 
  • For general information about the life cycle of your app, see Managing your app’s life cycle.
    • 이것도 각각 눌러서 읽어보면 좋을 것 같다.
    • In iOS 12 and earlier, you use your app delegate to manage major life cycle events in your app. 
      • 이 기능이 iOS 13 이후로는, SceneDelegate로 넘어갔다! (라이프사이클 관련 기능들)
      • 어플 전반적으로 초기화 or 챙겨줘야 하는 데이터와 동작들을 다룬다. (UserDefaults 관련 코드들 등등)

 

//
//  AppDelegate.swift
//  Week2
//
//  Created by 김소현 on 2022/09/27.
//

import UIKit

@main // LifeCycle의 시작점
class AppDelegate: UIResponder, UIApplicationDelegate {



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


}

 

 

 

 

 

2. SceneDelegate

 

https://sueaty.tistory.com/134

https://velog.io/@loinsir/iOS-AppDelegate-SceneDelegate

https://developer.apple.com/documentation/uikit/uiscenedelegate

 

Apple Developer Documentation

 

developer.apple.com

 

@MainActor protocol UISceneDelegate

 

Use your UISceneDelegate object to manage life-cycle events in one instance of your app’s user interface. This interface defines methods for responding to state transitions that affect the scene, including when the scene enters the foreground and becomes active, and when it enters the background. Use your delegate to provide appropriate behavior when these transitions occur. For example, finish critical tasks and quiet your app when it enters the background.

Don’t create UISceneDelegate objects directly. Instead, specify the name of your custom delegate class as part of the configuration data for your scenes. You can specify this information in your app’s Info.plist file, or in the UISceneConfiguration object you return from your app delegate’s application(_:configurationForConnecting:options:) method. For more information about how to configure scenes, see Specifying the scenes your app supports.

 

 

원래 iOS 13이전에는 디폴트로 앱은 단 하나의 window만 있음

-> 다중 윈도우가 지원되면서, 정확히 말하자면 window라는 개념이 scene으로 대체됨

    &  AppDelegate의 역할 중 UI LifeCycle이 SceneDelegate로 옮겨갔다.

- ex) 네비게이션 뷰컨트롤러 관련된 기본 설정들, window 개념 등등 

 

 

//
//  SceneDelegate.swift
//  Week2
//
//  Created by 김소현 on 2022/09/27.
//

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


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

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

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

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

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

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


}