iOS14后SwiftUI添加AppDelegate生命周期

1个月前 73次点击 来自 SwiftUI

原文链接:SwiftUI app life cycle iOS14 where to put AppDelegate code?

iOS14后SwiftUI去除了AppDelegate & SceneDelegate,而我们在开发中难免需要在App启动前初始化一些数据,以下是弥补方法:

import SwiftUI
import UIKit

// no changes in your AppDelegate class
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        print(">> your code here !!")
        return true
    }
}

@main
struct Testing_SwiftUI2App: App {

    // inject into SwiftUI life-cycle via adaptor !!!
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

如果你只是需要初始化一些简单的数据,则可以直接在init方法中实现即可:

import SwiftUI

@main
struct MyApp: App {
  
  init() {
    在这初始化数据()
  }
  
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}
Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识

本站文章全部采用 CC BY 4.0 协议,欢迎转载

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签