The Complete Tutorial on iOS/iPhone Custom URL Schemes

NoteSince the introduction of custom URL schemes, this post has consistently been the top read content on the blog. Although much is the same, there are a few nuances that have changed. This is a re-write of the original post, updated for the latest iOS and Xcode versions.

One of the coolest features of the iPhone/iOS SDK is an application’s ability to “bind” itself to a custom URL scheme and for that scheme to be used to launch the application from either a browser or from another application.

Registering a Custom URL Scheme

The first step is to create a custom URL scheme – start by locating and clicking on the project info.plist in the Xcode Project Navigator. With the plist displayed in the right pane, right click on the list and select Add Row:

From the list presented scroll down and select URL types.

iOS Custom URL Scheme

Open the directional arrow and you’ll see Item 0, a dictionary entry. Expand Item 0and you will see URL Identifier, a string object. This string is the name for the custom URL scheme you are defining. It’s recommended to ensure uniqueness of the name that you reverse domain name such as com.yourCompany.yourApp.

urlScheme2a

Tap on Item 0 and add a new row, select URL Schemes from the drop-down and tap Enter to complete the row insert.

iOS Custom URL Scheme

Notice URL Schemes is an array, allowing multiple URL schemes to be defined for an application.

iOS Custom URL Scheme

Expand the array and tap on Item 0. This is where you will define the name for the custom URL scheme. Enter just the name, do not append :// – for instance, if you enter iOSDevApp, your custom url will be iOSDevApp://

iOS Custom URL Scheme

Here is how the complete definition looks at this point:

iOS Custom URL Scheme

Although I appreciate Xcode’s intention when using descriptive names, I find it helpful to see the actual keys created. Here’s a handy trick, right-click on the plist and select Show Raw Keys/Values, the output will look as follows:

iOS Custom URL Scheme

There’s another output format that also has merit, XML, as it’s much easier to see the structure of the dictionary and the nested array and its entries. Tap the plist and this time choose Open As – Source Code:

iPhone Custom URL Scheme

Calling Custom URL Scheme from Safari

With the URL scheme defined, we can run a quick test to verify the app can be called as expected using the URL. Before we do that, I’ll create a barebones UI so we can identify the app with the custom URL. The app contains nothing more than a UILabel with the text “App With Custom URL.” Download source for creating iOS App with Custom URL Scheme.

iOS App with Custom URL

Using the simulator, here’s how to call the app:

– Run the application from within Xcode
– Once installed, the custom URL scheme will now be registered
– Close the app via the Hardware menu in simulator and choose Home
– Start Safari
– Enter the URL scheme defined previously in the browser address bar (see below)

Call Custom URL Scheme from Safari

At this point Safari will close and the app will be brought to the foreground. Congratulations, you’ve just called an iPhone application using a custom URL scheme!

Calling Custom URL Scheme from Another iPhone App

Let’s take a look at how to call the custom URL scheme from another iPhone application. Again, I’ve created a very simple iPhone application with nothing more than a UILabel and a UIButton – the former shows a message that this is the app that will call another app via a custom URL scheme, the button starts that process.Download source for creating iOS App to call Custom URL Scheme.

iPhone app that call Custom URL Scheme

The code inside the buttonPressed manages the URL processing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (void)buttonPressed:(UIButton *)button
{
  NSString *customURL = @"iOSDevTips://";
 
  if ([[UIApplication sharedApplication] 
    canOpenURL:[NSURL URLWithString:customURL]])
  {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
  }
  else
  {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL error"
                          message:[NSString stringWithFormat:
                            @"No custom URL defined for %@", customURL]
                          delegate:self cancelButtonTitle:@"Ok" 
                          otherButtonTitles:nil];
    [alert show];
  }    
}

Line 5 we check to see if the custom URL is defined, and if so, use the shared application instance to open the URL (line 8). The openURL: method starts the application and passes the URL into the app. The current application is exited during this process.

Passing Parameters To App Via Custom URL Scheme

Chances are you’ll need to pass parameters into the application with the custom URL definition. Let’s look at how we can do this with.

The NSURL class which is the basis for calling from one app to another conforms to the RFC 1808 (Relative Uniform Resource Locators). Therefore the same URL formatting you may be familiar with for web-based content will apply here as well.

In the application with the custom URL scheme, the app delegate must implement the method with the signature below:

- (BOOL)application:(UIApplication *)application 
  openURL:(NSURL *)url 
  sourceApplication:(NSString *)sourceApplication 
  annotation:(id)annotation

The trick to passing in parameters from one app to another is via the URL. For example, assume we are using the following custom URL scheme and want to pass in a value for a ‘token’ and a flag indicating registration state, we could create URL as follows:

NSString *customURL = @"iOSDevTips://?token=123abct&registered=1";

As in web development, the string ?token=123abct&registered=1 is known as the query string.

Inside the app delegate of the app being called (the app with the custom URL), the code to retrieve the parameters would be as follows:

1
2
3
4
5
6
7
8
9
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
        sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  NSLog(@"Calling Application Bundle ID: %@", sourceApplication);
  NSLog(@"URL scheme:%@", [url scheme]);
  NSLog(@"URL query: %@", [url query]);
 
  return YES;
}

The output from the app with the custom URL (using my Bundle ID), when called from another app, is as follows:

Calling Application Bundle ID: com.3Sixty.CallCustomURL
URL scheme:iOSDevTips
URL query: token=123abct&registered=1

Take note of the ‘Calling Application Bundle ID’ as you could use this to ensure that only an application that you define can interact directly with your app.

Let’s change up the delegate method to verify the calling application Bundle ID is known:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
        sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  // Check the calling application Bundle ID
  if ([sourceApplication isEqualToString:@"com.3Sixty.CallCustomURL"])
  {
    NSLog(@"Calling Application Bundle ID: %@", sourceApplication);
    NSLog(@"URL scheme:%@", [url scheme]);
    NSLog(@"URL query: %@", [url query]);
 
    return YES;
  }
  else
    return NO;
}

It’s important to note that you cannot prevent another application from calling your app via custom URL scheme, however you can skip any further processing and return NO as shown above. With that said, if you desire to keep other apps from calling your app, create a unique (non-obvious) URL scheme. Although this will guarantee you app won’t be called, it will make it more unlikely.

Custom URL Scheme Example Projects

I realize it can be a little tricky to follow all the steps above. I’ve included two (very basic) iOS apps, one that has the custom URL scheme defined and one that calls the app, passing in a short parameter list (query string). These are good starting points to experiment with custom URL’s.

Additional Resources

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值