Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally compile for tvOS in Swift

Tags:

ios

swift

tvos

How do I conditionally compile code for iOS and tvOS in the same file in the Swift language? I have tried all the Objective-C style #if etc. for TARGET_OS_TV as mentioned in the Apple docs, and some other answers. But I have not found a working solution for Swift code.

like image 796
Pop Avatar asked Feb 04 '16 13:02

Pop


4 Answers

#if os(OSX)
// compiles for OS X
#elseif os(iOS)
// compiles for iOS
#elseif os(tvOS)
// compiles for TV OS
#elseif os(watchOS)
// compiles for Apple watch
#endif
like image 52
Lubos Avatar answered Nov 15 '22 02:11

Lubos


This is also covered by Apple under the heading Targeting Apple TV in Your Apps

Listing 1-1 Conditionalizing code for tvOS in Objective-C

 #if TARGET_OS_TV
     NSLog(@"Code compiled only when building for tvOS.");
 #endif

Listing 1-2 Conditionalizing code for tvOS in Swift

#if os(tvOS)
NSLog(@"Code compiled only when building for tvOS.");
#endif

if #available(tvOS 9.1,*) {
    print("Code that executes only on tvOS 9.1 or later.")
}
like image 36
noelicus Avatar answered Nov 15 '22 03:11

noelicus


#if <build configuration> && !<build configuration>
statements
#elseif <build configuration>
statements
#else
statements
#endif

Where build configuration can be :-
os(abc) where valid values for abc are OSX, iOS, watchOS, tvOS, Linux
arch(abc) where valid values for abc are x86_64, arm, arm64, i386

See Apple docs here:

like image 5
Pop Avatar answered Nov 15 '22 02:11

Pop


I don't have a documentation reference -- though I'd like one -- but I've seen Apple sample code with sections like:

    #if os(iOS) || os(tvOS)
    #endif
like image 3
Phillip Mills Avatar answered Nov 15 '22 02:11

Phillip Mills