Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...