在Swift中,从App Extension目标运行时,如何忽略一部分代码?

问题描述 投票:0回答:1

有一个 类似问题 在Objective-C上工作,但我在Swift中尝试了同样的代码,但它从来没有执行过,无论是在主应用程序中,还是在动作扩展中。

我的情况和上面问题中的情况类似,也就是说,当从主应用程序中运行时,我想使用的是 UIApplication.shared.open 来打开Safari中的链接,但我想忽略App Extension上的这部分代码。

问题不在于发现应用是否从App Extension运行,而是在为App Extension构建时忽略这段代码,这样编译器就不会在构建时给我以下错误。

enter image description here

ios swift ios-app-extension
1个回答
0
投票

你可以为扩展目标引入一个新的自定义标志(类似于DEBUG标志)。在你的构建设置中寻找自定义标志并添加一个新的标志(例如 "EXTENSION")。就像截图中的那样,但也可以在发布时这样做。Extension Configuration

在你的代码中,你可以这样做

#if EXTENSION
    // here goes code that is only compiled in the extension
#else 
    // here goes code that is only compiled outside the extension 
#end

0
投票

更新:请阅读苹果提供的 关于应用扩展的文件:

部分API对应用扩展不可用

由于其在系统中的重点作用,应用程序扩展没有资格参加某些活动。应用程序扩展不能。

  • 访问一个 Application.shared 对象,因此不能使用该对象上的任何方法。

- 苹果,应用扩展编程指南

要想通过代码找到正在运行的扩展,其实很简单,只需这样做。

let bundleUrl: URL = Bundle.main.bundleURL
let bundlePathExtension: String = bundleUrl.pathExtension
let isAppex: Bool = bundlePathExtension == "appex"

// `true` when invoked inside the `Extension process`
// `false` when invoked inside the `Main process`
© www.soinside.com 2019 - 2024. All rights reserved.