Monday, January 30, 2012

Shorten a URL Using Bit.ly in Objective-C

This is a quick and dirty way to shorten a URL using the bit.ly API in Objective C. You will need to register with bit.ly and obtain a login name and API key. The code below will shorten a URL where BitLyLogin is your bit.ly login, BitLyAPIKey is your bit.ly API Key and shortenURL is the URL that you wish to shorten. This code should return nil if it is unable to connect to bit.ly but will return the text of an error message if it fails.


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

1 comment: