title: AFNetworking upload task with credentials (HTTP Basic Auth)
body: <p>I need to upload video files from my app to a server. I tried doing so via <code>[AFHTTPRequestOperationManager post:parameters:success:failure]</code> but unfortunately kept getting request timeouts. I'm now trying something similar to <em>Creating an Upload Task</em> from <a href="https://github.com/AFNetworking/AFNetworking" rel="nofollow noreferrer">the AF Docs</a>.</p>
  
  <p>I read <a href="https://stackoverflow.com/questions/18424408/settaskdidreceiveauthenticationchallengeblock-in-afnetworking-2-0">on SO</a> and the <a href="http://cocoadocs.org/docsets/AFNetworking/2.0.1/Classes/AFURLSessionManager.html#//api/name/setSessionDidReceiveAuthenticationChallengeBlock:" rel="nofollow noreferrer">AF Docs</a> about <code>setSessionDidReceiveAuthenticationChallengeBlock:</code> and tried to implement the whole upload malarky as follows:</p>
  
  <pre><code>__block ApiManager *myself = self;
  
  // Construct the URL
  NSString *strUrl = [NSString stringWithFormat:@"%@/%@", defaultUrl, [self getPathForEndpoint:endpoint]];
  NSURL *URL = [NSURL URLWithString:strUrl];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  [request setHTTPMethod:@"POST"];
  
  // Build a session manager
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  
  // Set authentication handler
  [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
      *credential = myself.credentials;
      return NSURLSessionAuthChallengeUseCredential;
  }];
  
  
  // Create the upload task
  NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
      if (error) {
          [myself endpoint:endpoint returnedFailure:error];
      } else {
          [myself endpoint:endpoint returnedSuccess:responseObject];
      }
  }];
  
  // and run with it
  [uploadTask resume];
  </code></pre>
  
  <p>The <code>myself.credentials</code> object has been set previously to have the correct username and password. Whenever this request fires, I get <code>401 unauthorised</code> as a response. I tried putting <code>NSLog(@"CHALLENGE")</code> inside the challenge block above, but it never seems to get called, so AFNetworking isn't giving me a way to supply credentials. I know that this works perfectly well on the server side because I've tested it with Postman.</p>
  
  <p>How can I get AFNetworking to let me supply credentials for HTTP Basic Auth with this upload task?</p>