【问题标题】:In Swift, how to ignore a part of the code when running from an App Extension target?在 Swift 中,从 App Extension 目标运行时如何忽略部分代码?
【发布时间】:2020-06-02 18:53:25
【问题描述】:

有一个 similar question 可以在 Objective-C 上运行,但我在 Swift 中尝试了相同的代码,但它从不执行,无论是在主应用程序中,还是在操作扩展中。

我的情况和上面的问题类似,就是从主应用运行的时候想用UIApplication.shared.open在Safari中打开一个链接,但是我想忽略上面的这部分代码应用扩展。

问题不是找出应用程序是否从应用程序扩展运行,而是在为应用程序扩展构建时忽略代码,因此编译器在构建时不会给我以下错误:

【问题讨论】:

    标签: ios swift ios-app-extension


    【解决方案1】:

    您可以为扩展目标引入一个新的自定义标志(类似于调试标志)。在您的构建设置中查找自定义标志并添加一个新标志(例如“EXTENSION”)。就像这里的截图一样,也是为了发布。

    在您的代码中,您可以执行类似的操作

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

    【讨论】:

    • 其实是#endif
    【解决方案2】:

    更新:请阅读苹果提供的documentation on App Extensions

    某些 API 不适用于应用扩展

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

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

    - Apple,应用程序扩展编程指南

    要通过代码以编程方式查找它是否是正在运行的扩展,这非常简单,只需执行以下操作:

    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`
    

    【讨论】:

    • 谢谢,但这并不会在为 App Extension 构建时忽略代码,这会导致我在问题中分享的编译器错误。
    • 查看我的更新。您可能想根据苹果文档更新目标中的文件。
    猜你喜欢
    • 2016-05-24
    • 2012-06-22
    • 2023-04-06
    • 2012-05-16
    • 2018-03-08
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多