title: Trouble getting a 401 response (unauthorized) from an iPhone app
body: <p>I have a synchronous method to send out requests that looks like the following:</p>
  
  <pre><code>+ (NSString *)sendRequest:(NSMutableURLRequest *)request {
      NSHTTPURLResponse *response;
      NSError *error;
  
      NSData *responseData = 
   [NSURLConnection sendSynchronousRequest:request                         
          returningResponse:&amp;response 
             error:&amp;error];
  
   NSLog(@"response = %@", response);
   NSLog(@"error = %@", [error localizedDescription]);
  
      NSString *responseString = 
   [[NSString alloc] initWithData:responseData 
          encoding:NSUTF8StringEncoding];
      [responseString autorelease];
  
      NSLog(@"%@: %@", [request HTTPMethod], [request URL]);
      NSLog(@"Response Code: %d", [response statusCode]);
      NSLog(@"Content-Type: %@", [[response allHeaderFields] 
                                  objectForKey:@"Content-Type"]);
      NSLog(@"Response: %@\n\n", responseString);   
  
      return responseString;
  }
  </code></pre>
  
  <p>For a particular request, I am getting a null response with an error saying "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)"</p>
  
  <p>According to the <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/uid/TP40003793-CH3g-SW40" rel="nofollow">Foundation constants reference</a> this code is NSURLErrorUserCancelledAuthentication which is described as</p>
  
  <blockquote>
    <p>Returned when an asynchronous request
    for authentication is cancelled by the
    user.</p>
    
    <p>This is typically incurred by clicking
    a "Cancel" button in a
    username/password dialog, rather than
    the user making an attempt to
    authenticate.</p>
  </blockquote>
  
  <p>However, I there is no user clicking cancel.  I am simply making a request to retrieve a list of events without being authorized and therefore the 401 I return should produce an unauthorized response, not a null response with a NSURLErrorUserCancelledAuthentication error.  My Rails code that returns this response is the following:</p>
  
  <pre><code>def require_auth
      # Return unauthorized if the API call was not made by an authorized user
      unless current_user
        respond_to do |format|
          #format.json { render :text =&gt; "Unauthorized", :status =&gt; :unauthorized }
          format.json { head :unauthorized }
          format.xml { head :unauthorized }
        end
      end   
  end
  </code></pre>
  
  <p>and the output from my Rails log looks like this:</p>
  
  <pre><code>Started GET "/events.json" for
  127.0.0.1 at Fri Jan 07 10:51:47 -0500 2011   
  Processing by EventsController#index as JSON Completed 401 Unauthorized in 0ms
  </code></pre>
  
  <p>Does anyone know why this is happening and how to create the correct response?</p>