iOS 14.5 or 14.6 onwards accessing UIApplication.shared.open or UIApplication.shared.openURL in Share Extension gives "APPLICATION_EXTENSION_API_ONLY"

Prior to iOS 14.5 or 14.6, we could launch the main app from a share extension by setting Require Only App-Extension-Safe API to NO and using:

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

But iOS 14.5 or 14.6 onwards, we get this error when building:

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

Is there a way to launch the main app from share sheet extension in iOS 14.5/14.6?

Upvotes: 2

Views: 1583

Answers (1)

I figured out a solution which lets you launch the main app while keeping Require Only App-Extension-Safe API to YES.

Set the Require Only App-Extension-Safe API to YES as Apple wants you to.

Then use this in the Extension:

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)

Upvotes: 6

Related Questions