Search code examples
iosobjective-ciphoneframeworkswatchkit

It is possible to detect if my framework is running as part of the main app or an extension?


In an iOS or OS X Framework, which contains common code for both its App, and app Extensions, is there a way to detect if the code is being run under the main app, or one of its extensions? Specifically I'd like to detect if the framework is being used as part of a WatchKit extension as opposed to within the iPhone part of the App.

UIDevice.currentDevice always returns the iPhone as that is what is running the code. I believe I could check if WKInterfaceDevice exists, but that doesn't seem too elegant.


Solution

  • One option is to check the file extension of the current target. This has the advantage that it works in shared libraries and frameworks, whereas other options often only work within a target itself:

    + (BOOL) isAppExtension
    {
        return [[[NSBundle mainBundle] executablePath] containsString:@".appex/"];
    }
    

    This answer was informed by this question and answer. Those answers also outline how to set a preprocessor macro, which would be another good option in some cases, though that wouldn't be accessible from your framework.

    I've not marked this question as a duplicate of that one, however, as these options are generic to all App extensions, neither is particularly elegant, and there may be WatchKit-specific options for what you're trying to achieve.