The answer from @the.blaggy is really helpful, thanks a lot for the main idea.
I just had no AppDelegate
and SceneDelegate
to copy these two delegate classes from iOS 13 Xcode projects. I just need to support iOS13+ and macOS using same new SwiftUI views instead of creating old UIKit and AppKit ones.
AppDelegate
allows us to use configurationForConnecting
directly in Swift instead of using plist file.
And @UIApplicationDelegateAdaptor
allows us to use same AppDelegate
for iOS14+.
So, I've wrote MainAppWrapper
, MainApp
, AppDelegate
, SceneDelegate
in one file.
The file can be used as a start template for any SwiftUI project to run same SwiftUI's ContentView()
under any OS: iOS13, iOS14+, macOS.
Just replace a whole @main struct
onto this code and you will see same ContentView()
under all OS.
import SwiftUI
@main
struct MainAppWrapper {
static func main() {
if #available(iOS 14.0, *) {
MainApp.main()
}
else {
#if os(iOS)
UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil,
NSStringFromClass(AppDelegate.self))
#endif
}
}
}
@available(iOS 14.0, *)
struct MainApp: App {
#if os(iOS)
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
#if os(iOS)
class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject {
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
let config = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
config.delegateClass = SceneDelegate.self
return config
}
}
class SceneDelegate: NSObject, UIWindowSceneDelegate, ObservableObject {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if #unavailable(iOS 14.0) {
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
}
}
#endif