3

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...)

pd95
  • 1,999
  • 1
  • 20
  • 33
  • This problem is gone with macOS 13. `if #available(macOS 12, *)` has been implemented there. – pd95 Jun 19 '22 at 10:54

1 Answers1

1

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
}
pd95
  • 1,999
  • 1
  • 20
  • 33
  • See also my answer which applies to cross-platform conditional compilation: https://stackoverflow.com/questions/24369272/swift-ios-deployment-target-command-line-flag/71099967#71099967 – pd95 Feb 13 '22 at 17:38
  • It's really disappointing we have to jump through so many hoops just to support older iOS versions, especially when availability is built into result builders as a special case (`buildLimitedAvailability`)! – halleygen Apr 08 '22 at 01:42