Josh Josh - 1 year ago 66
Android Question

Android / iOS - Custom URI / Protocol Handling

Is there a way to define some kind of handling mechanism in Android and iOS that would allow me to do intercept either of the following:

- or -

I'd like to 'listen' for either the protocol or the host, and open a corresponding Activity / ViewController.

I'd like too if these could be as system wide as possible. I imagine this will be more of an issue on iOS, but I'd ideally be able to click either of those two schemes, as hyperlinks, from any app. Gmail, Safari, etc.

Answer Source

For iOS, yes, you can do two things:

  1. Have your app advertise that it can handle URL's with a given scheme.

  2. Install a protocol handler to handle whatever scheme you like.

The first option is pretty straightforward, and described in Implementing Custom URL Schemes. To let the system know that your app can handle a given scheme:

  • update your app's Info.plist with a CFBundleURLTypes entry

  • implement -application:didFinishLaunchingWithOptions: in your app delegate.

The second possibility is to write your own protocol handler. This works only within your app, but you can use it in conjunction with the technique described above. Use the method above to get the system to launch your app for a given URL, and then use a custom URL protocol handler within your app to leverage the power of iOS's URL loading system:

  • Create a your own subclass of NSURLProtocol.

  • Override +canInitWithRequest: -- usually you'll just look at the URL scheme and accept it if it matches the scheme you want to handle, but you can look at other aspects of the request as well.

  • Register your subclass: [MyURLProtocol registerClass];

  • Override -startLoading and -stopLoading to start and stop loading the request, respectively.

Read the NSURLProtocol docs linked above for more information. The level of difficulty here depends largely on what you're trying to implement. It's common for iOS apps to implement a custom URL handler so that other apps can make simple requests. Implementing your own HTTP or FTP handler is a bit more involved.

For what it's worth, this is exactly how PhoneGap works on iOS. PhoneGap includes an NSURLProtocol subclass called PGURLProtocol that looks at the scheme of any URL the app tries to load and takes over if it's one of the schemes that it recognizes. PhoneGap's open-source cousin is Cordova -- you may find it helpful to take a look.