在 Cocoa 中检索短 URL 的原始 URL 的最简单方法是什么?几行就可以搞定什么?
更新:我刚刚看到您的评论,并意识到它正在跟踪重定向。
查看委托(delegate)方法:connection:willSendRequest:redirectResponse:
,它告诉您它正在根据之前的响应重定向到这个新请求。
您可以从此处的新请求或重定向响应的 Location header 中获取展开后的 URL。
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.
原始答案如下...
将 NSURLConnection
与委托(delegate)一起使用。在您的委托(delegate)的 connection:didReceiveResponse:
方法中,获取 allHeaderFields
并读取“Location” header 的值。
类似:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Expanded URL = %@", [[(NSHTTPURLResponse *)response allHeaderFields] objectForKey:@"Location"]);
}
我会创建一个小的 URLExpander
类来亲自执行此操作,其签名类似于:
+(void)asyncExpandURL:(NSURL *)aURL didExpandTarget:(id)target selector:(SEL)selector;
然后在您的消息中传回两个参数,一个用于短 URL,一个用于长 URL。
我是一名优秀的程序员,十分优秀!