如何检测代码是否在Main App或App Extension Target中运行? [英] How to detect if code is running in Main App or App Extension Target?
问题描述
如果您在App Extension中运行,是否有人知道如何从代码中进行检测?
Does anyone know how you detect from within your code if you're running inside an App Extension?
我有一个可以在应用程序和扩展程序之间共享类的应用程序.该应用程序代码使用[UIApplication sharedApplication]
,但扩展名中无法使用此代码,因此不会编译为:
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"不可用:iOS(应用程序扩展)不可用
'sharedApplication' is unavailable: not available iOS (App Extension)
因此,我需要一种方法来检测自己是否在扩展程序中,并在这种情况下使用sharedApplication
的替代方法.
So I need a way to detect that I'm in the extension and use an alternative to sharedApplication
if that's the case.
推荐答案
您可以使用预处理器宏:
You can use a preprocessor macro:
在项目设置中,使用顶部栏中的下拉菜单选择扩展目标:
In the project settings use the dropdown in the topbar to select your extension target:
然后:
- 点击
Build Settings
- 在
Apple LLVM 6.0 - Preprocessing
下找到(或搜索)Preprocessor Macros
- 在调试和发布部分中添加
TARGET_IS_EXTENSION
或您选择的其他任何名称.
- 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.
然后在您的代码中:
#ifndef TARGET_IS_EXTENSION // if it's not defined
// Do your calls to UIApplication
#endif
这篇关于如何检测代码是否在Main App或App Extension Target中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!