Search code examples
objective-ccocoashort-url

Simplest way to get a long URL for a shortened URL in Cocoa?


What is the simplest way to retrieve the original URL for a short URL in Cocoa? Anything that can be done in just a few lines?


Solution

  • UPDATE: I just saw your comment and realised it's following the redirect.

    See the delegate method: connection:willSendRequest:redirectResponse:, which tells you it's doing a redirect to this new request, based on the previous response.

    You can get the expanded URL either from the new request here, or from the Location header of the redirect response.

    Discussion If the delegate wishes to cancel the redirect, it should call the connection object’s cancel method. Alternatively, the delegate method can return nil to cancel the redirect, and the connection will continue to process. This has special relevance in the case where redirectResponse is not nil. In this case, any data that is loaded for the connection will be sent to the delegate, and the delegate will receive a connectionDidFinishLoading or connection:didFailLoadingWithError: message, as appropriate.

    Original answer follows...

    Use NSURLConnection with a delegate. In your delegate's connection:didReceiveResponse: method, fetch allHeaderFields and read the value of the "Location" header.

    Something like:

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        NSLog(@"Expanded URL = %@", [[(NSHTTPURLResponse *)response allHeaderFields] objectForKey:@"Location"]);
    }
    

    I'd create a little URLExpander class to do this personally, with a signature something like:

    +(void)asyncExpandURL:(NSURL *)aURL didExpandTarget:(id)target selector:(SEL)selector;
    

    Then just pass back two arguments in your message, one for the short URL, one for the long.