SwiftUI项目降级到iOS13后main/Scene/WindowGroup报错如何适配
兼容iOS13的SwiftUI入口调整方案
第一步:给原有入口添加版本限定
首先修改原MyProjectApp.swift文件,给基于App协议的入口添加iOS14+的可用性标记,移除原来的全局@main注解:
@available(iOS 14.0, *) struct MyProjectApp: App { let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) } } }
第二步:新增跨版本兼容的全局入口
新建一个Swift文件,命名为AppMain.swift,作为全局统一的入口,根据系统版本分发不同的启动逻辑:
import UIKit import SwiftUI // 全局主入口 @main struct AppMain { static func main() { if #available(iOS 14.0, *) { MyProjectApp.main() } else { // iOS13及以下走UIKit的AppDelegate启动逻辑 UIApplicationMain( CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self) ) } } } // iOS13兼容用的AppDelegate class AppDelegate: UIResponder, UIApplicationDelegate { let persistenceController = PersistenceController.shared var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) // 用UIHostingController包裹SwiftUI根视图,注入和原逻辑一致的环境变量 let rootView = ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) window?.rootViewController = UIHostingController(rootView: rootView) window?.makeKeyAndVisible() return true } }
第三步:检查配置项
如果你的项目Info.plist中存在Application Scene Manifest配置项,且不需要做多窗口支持,直接删除该配置即可,避免iOS13系统下出现启动异常
内容的提问来源于stack exchange,提问作者Thorvald
相关产品推荐
相关产品推荐

