iosswiftswiftuiios18

Support for older iOS versions when using DocumentGroupLaunchScene


I'm using the new DocumentGroupLaunchScene introduced in iOS 18.0 in my document-based SwiftUI app like this:

@main
struct MyApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: MyDocument()) { file in
            ContentView(document: file.$document)
        }
    
        if #available(iOS 18.0, *) {
            DocumentGroupLaunchScene {
                NewDocumentButton("Start")
            } background: {
                Color.blue
            }
        }
    }
}

When I run my app on a device with iOS 17 it crashes with this error:

Fatal error: if #available in SceneBuilder includes an unknown OS version

How can I use DocumentGroupLaunchScene while still supporting older iOS versions?


Solution

  • I managed to fix this crash by implementing two App structs:

    @main
    struct MyAppLauncher {    
        static func main() {
            if #available(iOS 18.0, *) {
                MyApp18.main()
            } else {
                MyApp17.main()
            }
        }
    }
    
    @available(iOS 18.0, *)
    struct MyApp18: App {
        var body: some Scene {
            DocumentGroup(newDocument: MyDocument()) { file in
                ContentView(document: file.$document)
            }
    
            DocumentGroupLaunchScene {
                NewDocumentButton("Start")
            } background: {                
                Color.blue
            }
    }
    
    struct MyApp17: App {
        var body: some Scene {
            DocumentGroup(newDocument: MyDocument()) { file in
                ContentView(document: file.$document)
            }
        }
    }