Tuesday 5 March 2013

Shortening URLs


I had some a to shorten URLs for an in-application Twitter client I'm working on and thought I would share my simple solution with you guys.
It's actually pretty straight forward and can be done in 1 line of code. I have broken it up into several for clarity.
NSString *url    = @"http://brandontreb.com";
NSString *apiEndpoint = [NSString stringWithFormat:@"http://api.tr.im/v1/trim_simple?url=%@",url];
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
   encoding:NSASCIIStringEncoding
   error : nil ] ;
NSLog ( @ "Long:% @ - Short:% @" , url, SHORTURL ) ;
 
/ / Outputs Long: http://brandontreb.com - Short: http://tr.im/MRDd
Pretty easy huh?
The magic here is in a method that Apple gave us as part of NSString. This method is called stringWithContentsOfURL. It will easily allow you to grave the text of any remote source.
I have used as Tr.im of example here because their service is very easy to use and has little overhead. I would have used bit.ly but they return a JSON string Which would then have to be parsed. Tr.im's trim_simple service simply outputs the string of the shortened URL.

No comments:

Post a Comment