首页 > 解决方案 > iOS 14.5 或 14.6 及更高版本在共享扩展中访问 UIApplication.shared.open 或 UIApplication.shared.openURL 会给出“APPLICATION_EXTENSION_API_ONLY”

问题描述

在 iOS 14.5 或 14.6 之前,我们可以通过设置并使用以下方式从共享扩展启动主应用Require Only App-Extension-Safe API程序NO

if #available(iOS 10.0, *) {
    UIApplication.shared.open(urlToOpen, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(urlToOpen)
}

但是 iOS 14.5 或 14.6 以后,我们在构建时收到此错误:

Application extensions and any libraries they link to must be built with the `APPLICATION_EXTENSION_API_ONLY` build setting set to YES.

有没有办法从 iOS 14.5/14.6 中的共享表扩展启动主应用程序?

标签: iosswiftobjective-cxcode

解决方案


我想出了一个解决方案,可以让您在启动主应用程序的同时Require Only App-Extension-Safe API保持YES.

Require Only App-Extension-Safe API按照YESApple的要求设置。

然后在扩展中使用它:

let sharedSelector = NSSelectorFromString("sharedApplication")
let openSelector = NSSelectorFromString("openURL:")

if let urlToOpen = URL(string: "YOURAPPURLSCHEME://whatever_you_need_to_pass"), UIApplication.responds(to: sharedSelector), let shared = UIApplication.perform(sharedSelector)?.takeRetainedValue() as? UIApplication, shared.responds(to: openSelector) {

    shared.perform(openSelector, with: urlToOpen)

}

//do the rest of extension completion stuff....
self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)

推荐阅读