Search code examples
iosxcodewatchkit

Using the same file with different flags in WatchKit and host App


I'm trying to use the same code in both my watchkit extension and host App, but with some additional code in the host App and some additional code in the watchkit extension. To do this I've added WATCH and APP swift flags on the respective targets. Problem is, when I look at my code with my App scheme selected, it doesn't syntax highlight the APP code but does highlight the WATCH code, and other code that refers to the APP code then fails to compile.

The watchkit extension is a target dependency of the App so I'm guessing it's something like it is compiling the code for the watch and then using the same compiled code for the App, although in the compile results I can see it is compiling with the correct flag and can't see any overlap between watchkit and App build paths, any ideas?


Solution

  • SWIFT version

    Use other swift flags in build settings of your WatchKit Extension target. For example, add a flag WATCH (must be prefixed with -D):

    enter image description here

    Then in your shared file add this code:

            #if WATCH
                NSLog("watch")
            #else
                NSLog("app")
            #endif
    

    Objective-C version

    Use preprocessor macros in build settings of your WatchKit Extension target. For example, add a macro WATCH = 1:

    enter image description here

    Then in your shared file add this code:

    #ifdef WATCH
        NSLog(@"watch");
    #else
        NSLog(@"app");
    #endif