iOS开发iOS基础知识

[iOS开发]iOS13 Scene Delegate

2020-07-04  本文已影响0人  codeTao

为了实现iPadOS支持多窗口,Xcode11后创建新工程默认会通过 UIScene 创建并管理多个 UIWindow 的应用,工程中除了 AppDelegate 外还会有一个 SceneDelegate。

一、SceneDelegate介绍

1)、Window与Scene

iOS13以后,SceneDelegate将负责AppDelegate的某些功能。 window(窗口)的概念被window(场景)的概念所代替, 一个scene现在可以作为您应用程序的用户界面和内容的载体。iOS13以前一个应用程序可以有不止一个window,同样现在一个应用程序也可以有不止一个scene。

2)、SceneDelegate三处新增内容

iOS13以后,Xcode新建iOS项目中有增加三处新增内容:

新增SceneDelegateClass
application(_:configurationForConnecting:options:) 
application(_:didDiscardSceneSessions:)

下面分别讲解下新增三处内容:

二、SceneDelegate三处新增内容详解

1)、SceneDelegate类

SceneDelegate和AppDelegate中方法名相似, 是任何应用程序生命周期都会调用方法。

//SceneDelegate.swift 代码
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }
    }

    func sceneDidDisconnect(_ scene: UIScene) { }

    func sceneDidBecomeActive(_ scene: UIScene) { }

    func sceneWillResignActive(_ scene: UIScene) { }

    func sceneWillEnterForeground(_ scene: UIScene) { }

    func sceneDidEnterBackground(_ scene: UIScene) { }
}

SceneDelegate其他方法:

2)、AppDelegate类新增两个方法

//AppDelegate.swift 代码
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        return true
    }
    // MARK: UISceneSession Lifecycle
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    }
}

在iOS13中AppDelegate中新增的两个函数是负责管理Senen Session的代理函数。在应用创建scene(场景)后,scene session对象将跟踪与该scene相关的所有信息。

这两个函数是:

3)、Info.plist 中的Application Scene Manifest

Info.plist文件文件包含App的配置信息,如App的名称,版本,支持的设备方向,现在我们可以通过配置Application Scene Manifest项来支持的不同场景。大多数应用程序只有一个场景,但是可以通过配置该项创建更多场景,如用于响应推送通知或特定操作的特定场景。

那么AppDelegate中的SceneDelegateUISceneSession和Info.plist中的Application Scene Manifest是如何一起创建多窗口应用的呢?

三、SceneDelegate适配

从iOS13开始AppDelegate不再有window属性,window属性被定义在SceneDelegate中。这是因为iOS13中AppDelegate的职责发现了改变:

因此,iOS13以前创建项目如果不需要多窗口就不需要任何改动,而iOS13以后创建新项目时,就要做一些适配:

1. 不需要多窗口(multiple windows)

如果使用纯代码来实现显示界面,需要在AppDelegate.h中手动添加window属性,添加以下代码即可:

class AppDelegate: UIResponder, UIApplicationDelegate {
    //手动添加window属性
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        self.window = UIWindow(frame:UIScreen.main.bounds)
        self.window!.backgroundColor = UIColor.white
        //设置root
        let rootVC = UIViewController()
        self.window!.rootViewController = rootVC
        self.window!.makeKeyAndVisible()
        return true
    }

    // MARK: UISceneSession Lifecycle
//    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
//        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
//    }
//    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
//    }
}

2. 支持多窗口适配

iOS 13后新项目中info.plist中的配置项Application Scene Manifest是针对iPad multiple windows功能推出的。在保留Application Scene Manifest配置项不予删除时(其中,项目是否支持多窗口功能是个可勾选项),AppDelegate的生命周期方法不再起作用,需要在SceneDelegate中使用UIScene提供的生命周期方法,并且需要针对 iOS 13 在Scene中配置和 iOS 13 以下在AppDelegate中做两套配置。

下面是纯代码实现界面显示的代码:
Swift适配代码步骤:

//SceneDelegate.swift
@available(iOS 13, *)  //在类的头部@available(iOS 13, *)添加即可
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
....
....
}
// AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    //手动添加window属性
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        if #available(iOS 13, *) {
            
        } else {
            window = UIWindow(frame:UIScreen.main.bounds)
            window!.backgroundColor = UIColor.blue
            //设置root
            let rootVC = UIViewController()
            window!.rootViewController = rootVC
            window!.makeKeyAndVisible()
        }
        return true
    }
    
    //新增方法添加@available(iOS 13, *)
    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    }
}
@available(iOS 13, *)
class 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 }
        let window = UIWindow(windowScene: windowScene)
        let vc = ViewController()
        vc.view.backgroundColor = .red
        let navigation = UINavigationController(rootViewController: vc)
        window.rootViewController = navigation
        window.makeKeyAndVisible()
        self.window = window
    }
...
...
}

OC适配代码:

// AppDelegate.m中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if (@available(iOS 13.0, *)) {

    } else {
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self.window setBackgroundColor:[UIColor whiteColor]];
        
        ViewController *vc = [[ViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        [self.window setRootViewController:nav];
        [self.window makeKeyAndVisible];
    }
    return YES;
}
// SceneDelegate.m中
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    
    //在这里手动创建新的window
    if (@available(iOS 13.0, *)) {
        UIWindowScene *windowScene = (UIWindowScene *)scene;
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self.window setWindowScene:windowScene];
        [self.window setBackgroundColor:[UIColor whiteColor]];
        
        ViewController *con = [[ViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:con];
        [self.window setRootViewController:nav];
        [self.window makeKeyAndVisible];
    }
}
func applicationWillResignActive(_ application: UIApplication) { }
...
...

四、SwiftUI中SceneDelegate

SwiftUI创建的iOS 13项目,所以SwiftUI应用程序主要依靠SceneDelegate来设置应用程序的初始UI。

SwiftUI项目info.plist文件中Application Scene Manifest项配置如下:

//SceneDelegate.swift
import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let contentView = ContentView()
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
.....
.....
}

上面的代码中发生了什么?
使用此方法可以有选择地配置UIWindow窗口并将其附加到提供的UIWindowScene场景。
如果使用storyboard,则window属性将自动初始化并附加到场景中。

将上边归纳如下内容:

上一篇下一篇

猜你喜欢

热点阅读