Search code examples
iphoneobjective-ciosios4

How to shorten a URL in objective C


I found several examples for shortening an URL. But none of them did not work for me. If anyone have working example, please share. What I have tried,

 NSString *apiEndpoint = [NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@",strUrl];
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
                                              encoding:NSASCIIStringEncoding
                                                 error:nil];
NSLog(@"Long: %@ - Short: %@",strUrl,shortURL);

NSString *shortenedURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apikey=%@&longUrl=%@&format=txt", @"[email protected]", @"R_2db6e96aad348b8c993acf6ba80884c4", strUrl]] encoding:NSUTF8StringEncoding error:nil];

NSLog(@"Shoted url %@", [shortenedURL JSONValue]);

Solution

  • just try bellow code for short url..

    1.try first this..

    NSString *urlstr = yourURL ;///here put your URL in string
    [urlstr retain];
    NSString *apiEndpoint = [NSString stringWithFormat:@"http://ggl-shortener.appspot.com/?url=%@",urlstr];
    [apiEndpoint retain];
    
    NSLog(@"\n\n APIEndPoint : %@",apiEndpoint);
    NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
                                                  encoding:NSASCIIStringEncoding
                                                     error:nil];
    shortURL = [shortURL stringByReplacingOccurrencesOfString:@"{\"short_url\":\"" withString:@""];
    shortURL = [shortURL stringByReplacingOccurrencesOfString:@"\",\"added_to_history\":false}" withString:@""];
    [shortURL retain];
    NSLog(@"Long: %@ - Short: %@",urlstr,shortURL);
    

    2.second way is bellow

    NSString *urlstr =[yourURL stringByReplacingOccurrencesOfString:@" " withString:@""];///your url string 
                [urlstr retain];
                NSString *apiEndpoint = [NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@",urlstr];
                [apiEndpoint retain];
    
                NSLog(@"\n\n APIEndPoint : %@",apiEndpoint);
                NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
                                                              encoding:NSASCIIStringEncoding
                                                                 error:nil];
    [shortURL retain];
        NSLog(@"Long: %@ - Short: %@",urlstr,shortURL);
    

    hope this help you...

    :)