Search code examples
ioshyperlinkurl-shortenerbit.lyaffiliate

IOS affiliate link shorten with bit.ly not working


I want to use bit.ly to track my itunes affiliate links. I get affiliate links from http://target.georiot.com. It works when oppening the direct link (going to itunes). But when i shorten the affiliate link with bitly, it doesn't go on the same page.

Here is the code for getting the shorten url:

NSString *longURL = link;
NSString *bitlyRequestURLString = [NSString stringWithFormat:@"http://api.bit.ly/shorten?version=2.0.1&format=xml&login=%@&apiKey=%@&longUrl=%@",
                                   @"myappname",
                                   @"myappidentifier",
                                   longURL];
NSURL *bitlyURL = [NSURL URLWithString:bitlyRequestURLString];

// get the short URL from bit.ly
NSError *error;
NSString *response = [NSString stringWithContentsOfURL:bitlyURL encoding:NSUTF8StringEncoding error:&error];

NSString *shortURL = @"";
NSArray *responseParts = [response componentsSeparatedByString:@"<shortUrl>"];

if ([responseParts count] > 1) {
    NSString *responsePart = [responseParts objectAtIndex:1];
    responseParts = [responsePart componentsSeparatedByString:@"</shortUrl>"];

    if ([responseParts count] > 0) {
        shortURL = [responseParts objectAtIndex:0];
    }
}

Last redirect link goes someting like "http://phobos.apple.com/WebObjects/...."

Any Ideas? Thanks


Solution

  • You probably need to URL encode your longURL before sending it in the query string to bit.ly

    You can use the NSString method stringByAddingPercentEscapesUsingEncoding:

    NSString *longURL = [link stringByAddingPercentEscapesUsingEncoding:
     NSASCIIStringEncoding];
    NSString *bitlyRequestURLString = [NSString stringWithFormat:@"http://api.bit.ly/shorten?version=2.0.1&format=xml&login=%@&apiKey=%@&longUrl=%@",
                                       @"myappname",
                                       @"myappidentifier",
                                       longURL];