Reputation: 3180
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.
Upvotes: 6
Views: 1371
Reputation: 3180
Specifically for WatchKit I came up with the following:
[[[NSBundle mainBundle] bundleIdentifier] hasSuffix:@"watchkitextension"];
Or in Swift:
NSBundle.mainBundle().bundleIdentifier?.hasSuffix("watchkitextension")
This relies on the fact that a WatchKit extension must have a bundle id ending in watchkitextension.
Upvotes: 3
Reputation: 20177
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.
Upvotes: 4