我目前正在使用 AFNetworking 发送 HTTP 请求。服务器当前设置为在失败和成功的情况下响应重定向到另一个 HTML 页面(我们的客户端可以控制服务器,如果没有很多官僚主义,我们无法更改其行为)。
我需要捕捉它何时重定向到成功的 HTML 页面,并且由于重定向而不会自动发布另一个 HTTP 请求后缀。
- (void) fetchHttpRequest: (void (^)(id result)) completionBlock
errorBlock: (void (^)(NSError * error, id result)) errorBlock
{
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"/"]];// replace with correct url
AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc]
initWithRequest:urlRequest];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation * operation, id result)
{
completionBlock(result);
}
failure:
^(AFHTTPRequestOperation * operation, NSError *error)
{
errorBlock(error, nil);
}];
// check the redirection
[operation setRedirectResponseBlock:
^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request,
NSURLResponse *redirectResponse)
{
NSString * reqUrlPath = @"/";// replace with success URL
if ([reqUrlPath isEqualToString:[[request URL] path]])
{
// success case
return nil;
}
else
{
// failure case
return request;
}
}];
[operation start];
}
在应用程序已经被重定向之前,操作的完成块不会捕获任何成功,这会导致失败。
它确实到达了// success case
重定向块中的 ,但由于所需的返回类型,我无法阻止代码尝试转到该位置的下一页。因此,在我定义 的地方completionBlock
,它会收到错误而不是完成。