title: AFNetworking: Prevent Redirect
body: <p>I am currently using AFNetworking to send off HTTP requests. The server is currently set up to respond with a redirect to another HTML page in both a fail and success scenario (Our client has control over the server and we cannot change its behavior without a lot of bureaucracy).</p>
  
  <p>I need to catch when it redirects to the success HTML page and not automatically post another HTTP request afterwords due to the redirect.</p>
  
  <pre><code>- (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];
  }
  </code></pre>
  
  <p>The completion block on the operation does not catch any successes until the app has already been redirected, which results in a failure.</p>
  
  <p>It does reach the <code>// success case</code> in the redirect block, but I cannot stop the code from attempting to go to the next page at that location due to the required return type. Thus, where I define the <code>completionBlock</code>, it receives an error instead of a completion.</p>