4

I am creating a Today extension. I have added all necessary files and getting a bunch of compile errors about

  • openUrl is not available
  • sharedApplication is not available
  • init on UIAlertView is not available

The files with these dependencies are built deep into my app (error handler on my networking layer, etc), and I know that they won't be used in the Today Extension, but in order to completely get rid of dependency in these files I need to refactor the entire app. Is there a way around this?

My code is Swift so I can't use compiler macros either to avoid executing these lines of code.

#if !TARGET_IS_TODAY_EXTENSION #endif

aryaxt
  • 76,198
  • 92
  • 293
  • 442

2 Answers2

5

You can use compiler macros, though it's not as flexible as with Objective-C (and IMO is slightly mis-designed). If you add something like -DTODAY_EXTENSION to the "Other Swift Flags" section of the build settings for the today extension, you can do something like this in code:

    #if TODAY_EXTENSION
        println("In today extension")
    #else
        println("Not in today ext")
    #endif

It just works. However:

  • The compiler seems to ignore macros with a value, so if you use something like -DTODAY_EXTENSION=1 it won't have any effect. Drop the value and make it -DTODAY_EXTENSION
  • #if works when checking the macro but #ifdef does not.

Apple has some documentation on this but I still had to experiment to get it working.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
0

If the code that uses .shared is in a framework (ie. cocoapod), then you cannot use compiler macros. There's an approach here that should work: iOS 8 Extension How To Detect Running

Community
  • 1
  • 1
xaphod
  • 6,392
  • 2
  • 37
  • 45