pd95
pd95

Reputation: 2642

Conditionally add commands to SwiftUI WindowGroup

With macOS 12 Apple fixed the omission of „Continuity Camera“ in SwiftUI by introducing the command group ImportFromDevicesCommands which can simply be added to a window.

But when you try to use it in an app supporting macOS 11 and 12, you are missing the conditionality support as it is common when combining SwiftUI views.

I have tried the following:

import SwiftUI

@main
struct ThrowAwayApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            if #available(macOS 12, *) {
                ImportFromDevicesCommands()
            }
        }
    }
}

But the compiler brings up the following error message:

Closure containing control flow statement cannot be used with result builder 'CommandsBuilder'

I understand the CommandsBuilder does not support buildIf(), buildEither(first:) and buildEither(second:) and is therefore missing the if-block support as for SwiftUI views.

Is there a way to conditionally add commands to the WindowGroup? Can I do some trickery with @available? (I'm really missing the @unavailable...)

Upvotes: 3

Views: 493

Answers (1)

pd95
pd95

Reputation: 2642

I've come up with a solution which allows me to check whether code is compiled for macOS 11 or macOS 12 by defining derived User-Defined build configuration in Xcodes project settings:

TARGET_MAJOR = $(SUPPORTED_PLATFORMS:upper)$(MACOSX_DEPLOYMENT_TARGET:base)

And then referring to this variable in the Other Swift Flags

OTHER_SWIFT_FLAGS = -DTARGET_$(TARGET_MAJOR)

Afterwards I can conditionally compile code for macOS 12 by using:

WindowGroup {
    ContentView()
}
.commands {
#if TARGET_MACOSX12
    ImportFromDevicesCommands()
#elseif TARGET_MACOSX11
    #warning("ImportFromDevicesCommands not implemented")
#endif
}

Upvotes: 1

Related Questions