目錄
???????前言
一、AppDelegate和SceneDelegate的關系
1.AppDelegate
2.SceneDelegate
3.info.plist配置
4.生命周期方法對比
1.應用啟動
2.進入前臺
3.進入后臺
5.何時使用AppDelegate和SceneDelegate
1.AppDelegate
2.SceneDelegate
前言
????????在iOS 13及之后的版本中,蘋果引入了UIScene
和UISceneDelegate
,將應用程序的生命周期管理分成了多個場景(Scene),使得多窗口支持成為可能。SceneDelegate
和 AppDelegate
分別負責不同方面的應用程序生命周期和 UI 管理。
? ? ? ? 這篇博客主要介紹UISceneDelegate以及相關API的用法。
一、AppDelegate和SceneDelegate的關系
1.AppDelegate
? ? ? ? 1.主要用于處理應用程序級別的事件,如應用程序啟動、終止、進入前臺和后臺等。
? ? ? ? 2.在iOS 13之前,AppDelegate負責所有應用程序生命周期的管理
2.SceneDelegate
? ? ? ? 1.引入于iOS 13,用于管理單個窗口或場景的生命周期。
? ? ? ? 2.一個應用程序可以有多個SceneDelegate
實例,每個實例對應一個窗口或場景
? ? ? ? 3.主要用于處理與UI相關的生命周期事件,例如場景的創建、進入前臺、進入后臺等
? ?AppDelegate實例如下:
import UIKit@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?// 應用程序啟動時調用func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {// 初始化代碼return true}// 應用程序進入后臺時調用func applicationDidEnterBackground(_ application: UIApplication) {// 保存數據或釋放資源}// 應用程序進入前臺時調用func applicationWillEnterForeground(_ application: UIApplication) {// 恢復數據或資源}// 更多方法...
}
???SceneDelegate實例如下:
import UIKitclass SceneDelegate: UIResponder, UIWindowSceneDelegate {var window: UIWindow?// 場景連接時調用func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {guard let windowScene = (scene as? UIWindowScene) else { return }window = UIWindow(windowScene: windowScene)window?.rootViewController = ViewController() // 設置根視圖控制器window?.makeKeyAndVisible()}// 場景進入前臺時調用func sceneWillEnterForeground(_ scene: UIScene) {// 恢復數據或資源}// 場景進入后臺時調用func sceneDidEnterBackground(_ scene: UIScene) {// 保存數據或釋放資源}// 更多方法...
}
3.info.plist配置
????????要使SceneDelegate生效,需要在Info.plist中進行配置:
<key>UIApplicationSceneManifest</key>
<dict><key>UIApplicationSupportsMultipleScenes</key><true/><key>UISceneConfigurations</key><dict><key>UIWindowSceneSessionRoleApplication</key><array><dict><key>UISceneConfigurationName</key><string>Default Configuration</string><key>UISceneDelegateClassName</key><string>$(PRODUCT_MODULE_NAME).SceneDelegate</string></dict></array></dict>
</dict>
4.生命周期方法對比
1.應用啟動
????????AppDelegate: application(_:didFinishLaunchingWithOptions:)
??? ? ?SceneDelegate: scene(_:willConnectTo:options:)
2.進入前臺
????????AppDelegate: applicationWillEnterForeground(_:)
? ????????SceneDelegate: sceneWillEnterForeground(_:)
3.進入后臺
????????AppDelegate: applicationDidEnterBackground(_:)
? ??????SceneDelegate: sceneDidEnterBackground(_:)
5.何時使用AppDelegate和SceneDelegate
1.AppDelegate
?- 處理應用程序級別的事件,如推送通知的注冊、處理快捷方式、全局狀態保存等。
? - 與應用程序生命周期無關的設置和初始化。
2.SceneDelegate
?- 處理與單個UI場景相關的事件,如窗口管理、多任務處理等。
? - 每個窗口或場景特定的UI狀態管理。
通過引入`SceneDelegate`,蘋果提供了更好的方式來管理iPad的多窗口支持,并且更清晰地分離了應用程序的生命周期事件和UI相關的生命周期事件。這有助于開發者更好地組織代碼并支持復雜的應用程序功能。