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 fe开发者_开发问答w lines?
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.
there is no simple way, you have to request the short-url-providing-server and get the full url. This must be done with a url connection and maybe some logic behind to get the redirect link (I haven't tried yet)
If you don't want to make the request and follow the redirects, a simpler way is to use a link-lengthening service. Here are two simple APIs:
http://longurl.org/api/#expand-url
http://www.longurlplease.com/docs
I may post some code snippets soon especially if there is interest.
精彩评论