iPhone Coding Snippet – Shortening URLs

    • Tweet
    February 4th, 2020 Posted by: - posted under:Snippets

    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 grab the text of any remote source.

    I have used Tr.im as an 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.

    Sure Twitter may shorten links for you automatically, but what if you want to use a custom service? Or,…wait for it… use it for something other than Twitter (please post in the comments if you do. I would love to hear some other uses :))

    Questions? Comments? Complaints?

    Happy iCoding