通过阅读文档NSURLConnection
,该currentRequest
方法应该反映加载时可能发生的任何重定向:
当连接执行负载时,请求可能会由于协议规范化或由于以下重定向而改变。此方法用于检索当前值。
但是,当我检查它时currentRequest
,connectionDidFinishLoading:
它总是有原始请求的 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
会显示以 结尾的页面 URL Overview.html
,但它仍然显示301.html
。