如何检测代码是否在Main App或App Extension Target中运行? [英] How to detect if code is running in Main App or App Extension Target?

查看:174
本文介绍了如何检测代码是否在Main App或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:

然后:

  1. 点击Build Settings
  2. Apple LLVM 6.0 - Preprocessing下找到(或搜索)Preprocessor Macros
  3. 在调试和发布部分中添加TARGET_IS_EXTENSION或您选择的其他任何名称.
  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.

然后在您的代码中:

#ifndef TARGET_IS_EXTENSION // if it's not defined
    // Do your calls to UIApplication
#endif

这篇关于如何检测代码是否在Main App或App Extension Target中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆