objective-c – 为什么NSURLConnection的currentRequest在重定向后没有指出正确的URL?

通过阅读NSURLConnection的文档,currentRequest方法应该反映加载时可能发生的任何重定向:

As the connection performs the load, the request may change as a result of protocol canonicalization or due to following redirects. This method is be used to retrieve the current value.

但是,当我在connectionDidFinishLoading中检查currentRequest时:它始终具有原始请求的URL,即使检查响应数据显示重定向已成功完成. (见下面的人为例子)

我的问题是:为什么currentRequest不返回实际的当前请求?我做错了什么或这是预期的行为?如果这是预期的行为,那么currentRequest应该对什么有用?

@interface AppDelegate : UIResponder <UIApplicationDelegate, NSURLConnectionDataDelegate>
@property (strong, nonatomic) NSURLConnection *connection;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSURL *url = [[NSURL alloc] initWithString:@"http://jigsaw.w3.org/HTTP/300/301.html"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    return YES;
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    NSLog(@"willSendRequest // request: %@ // currentRequest: %@", request, [connection currentRequest]);
    return request;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"didFinishLoading // originalRequest: %@ // currentRequest: %@", [connection originalRequest], [connection currentRequest]);
}

@end

运行此示例为我提供以下输出:

2012-12-18 15:18:44.949 ConnectionTest[12534:c07] willSendRequest // request: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html> // currentRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html>
2012-12-18 15:18:44.954 ConnectionTest[12534:c07] willSendRequest // request: <NSURLRequest http://jigsaw.w3.org/HTTP/300/Overview.html> // currentRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html>
2012-12-18 15:18:44.955 ConnectionTest[12534:c07] didFinishLoading // originalRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html> // currentRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html>

我的期望是,对currentRequest的最后一次调用将显示以Overview.html结尾的页面URL,但它仍显示301.html.

最佳答案 我只想把这个问题归结为苹果不得不混淆文档.我可以通过检查响应对象来获取最终请求URL,但对我来说,一个名为currentRequest的东西应该反映在重定向之后发出的最后一个请求.

点赞