FizzBuzz
FizzBuzz

Reputation: 764

Unified openURL for framework + app + extension

I have a Swift application for iOS 8 that has an app component, an extension component, and a framework that contains a lot of shared resources - shared view controllers, shared assets, etc. At one point in the framework, I want to call

UIApplication.sharedApplication().openURL(someURL)

But if I do that when "Allow app extension API only" is checked, it errors because UIApplication.sharedApplication() is unavailable in extensions. If I uncheck that box, I get a warning that it may be unsafe to include the framework in the extension, and I'm worried that may lead to a rejection when it comes to submission time.

If this code were only used in extensions, I would use something like:

extensionContext.openURL(someURL, completionHandler: nil)

…but that doesn't work in standalone apps, only in extensions.

It's trivial to amend my code to ensure that the UIApplication.sharedApplication().openURL() line is never called by the extension, and the extensionContext.openURL() line is never called by the app, but that doesn't clear up the error - merely the presence of UIApplication.sharedApplication() in an extension API framework causes the error.

So, before I start looking into hacks, is there a clean solution that lets me called openURL and takes the correct action, without causing compile errors?

Thanks in advance!

Upvotes: 4

Views: 854

Answers (1)

Derrick Hathaway
Derrick Hathaway

Reputation: 1097

Declare a global 😱, Optional closure variable to open URLs in your shared framework.

public openURL: (NSURL->())? = nil

Then set it in your app delegate's application:didFinishLaunching:... like so:

openURL = { UIApplication.sharedApplication().openURL($0) }

Then you can call openURL from anywhere like this:

openURL?(NSURL(string: "http://stackoverflow.com/")!)

This statement will have no effect in your extensions because you will not have ever set openURL within the app extensions process.

Upvotes: 2

Related Questions