Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if code is running in Main App or App Extension Target?

Does anyone know how you detect from within your code if you're running inside an App Extension?

I have an app which shares classes between an app and an extension. The app code uses [UIApplication sharedApplication] but this isn't available from within an extension, so it won't compile saying:

'sharedApplication' is unavailable: not available iOS (App Extension)

So I need a way to detect that I'm in the extension and use an alternative to sharedApplication if that's the case.

like image 771
Mark Bridges Avatar asked Jul 30 '14 22:07

Mark Bridges


People also ask

What is a .app extension?

An app extension lets you extend custom functionality and content beyond your app and make it available to users while they're interacting with other apps or the system. You create an app extension to enable a specific task.

What is the iOS app extension?

App Extensions are an iOS feature that allows developers to extend the functionality and content of their app beyond the app itself, making it available to users in other apps or in the main operating system.

What is notification service extension?

A notification service app extension doesn't present any UI of its own. Instead, it's launched on demand when the system delivers a notification of the appropriate type to the user's device. You use this extension to modify the notification's content or download content related to the extension.

How do I use Xcode extension?

The easiest way to add an app extension target is to use an Xcode template that provides a target preconfigured for your extension point. To add a new target to your Xcode app project, choose File > New > Target. In the sidebar on the left side of the new target dialog, choose Application Extension for iOS or OS X.


1 Answers

You can use a preprocessor macro:

In the project settings use the dropdown in the topbar to select your extension target: enter image description here

Then:

  1. Click Build Settings
  2. Find (or search) Preprocessor Macros under Apple LLVM 6.0 - Preprocessing
  3. 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 
like image 180
Andrew Avatar answered Oct 01 '22 13:10

Andrew