How to detect if code is running in Main App or App Extension Target?
You can use a preprocessor macro:
In the project settings use the dropdown in the topbar to select your extension target:
Then:
- Click
Build Settings
- Find (or search)
Preprocessor Macros
underApple LLVM 6.0 - Preprocessing
- Add
TARGET_IS_EXTENSION
or any other name of your choice in both the debug and release sections.
Then in your code:
#ifndef TARGET_IS_EXTENSION // if it's not defined // Do your calls to UIApplication#endif
As Apple's documentation says:
When you build an extension based on an Xcode template, you get an extension bundle that ends in .appex.
So, we can use the following code:
if ([[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"]) { // this is an app extension}// Swift versionif Bundle.main.bundlePath.hasSuffix(".appex") { // this is an app extension}
The preprocessor macro will work mostly, but will not work in shared library (e.g. cocoapods or shared frameworks).
Alternatively you can use following code.
@implementation ExtensionHelpers+(BOOL) isAppExtension{ return [[[NSBundle mainBundle] executablePath] containsString:@".appex/"];}@end
This work by checking the bundle executablePath, as only App Extension has extension ".appex".