Supporting Custom URL Schemes in iOS App

To enable your iOS app to respond to custom URLs from third party application you need to do some changes. If you want the app to respond to click of following url scheme:

talsa://article/ios?id=201244075

The URL should follow format: scheme://host/path?query and the following changes need to be done in xcode project .plist file:

plist

The app delegate should provide a similar custom implementation:

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if ([[url absoluteString] hasPrefix:@"talsa"]) //talsa
    {
        NSDictionary* parameters = [self parseQueryString:[url query]];
        NSString* articleId = [parameters valueForKey:@"id"];
        if (articleId != nil)
        {
            //do something here, open a view or whatever
        }
        return YES;
    }
    return NO;
}

- (NSDictionary *)parseQueryString:(NSString *)query
{
    NSMutableDictionary *dict = [[[NSMutableDictionary alloc] init] autorelease];
    NSArray *pairs = [query componentsSeparatedByString:@"&"];

    for (NSString *pair in pairs)
    {
        NSArray *elements = [pair componentsSeparatedByString:@"="];
        NSString *key = [[elements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *val = [[elements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        [dict setObject:val forKey:key];
    }
    return dict;
}

In circumstances where url is more complicated e.g. it included another url as input parameter then URL would need to be specified in URL encoded form: http://www.w3schools.com/TAGS/ref_urlencode.asp i.e.

URL in encoded form:

scheme://url_identifier/ios?accesscode=123456789&callback=http%3A%2F%2Fwww%2Efoo%2Ecom

URL in normal form:

scheme://url_identifier/ios?accesscode=123456789&callback=http://www.foo.com
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s