title: NSURLSession and Authentication with credentials
body: <p>I am trying to grab data from a web server that requires authentication using NSURLSession. I have tried a couple of different ways and no luck. Here is what I have so far. It is getting to the protocol method didReceiveChallenge, but doesn't seem to be authenticating. And the data I receive back is null.</p>
  
  <p>I have checked the username/password they are correct. And I have double checked the URL is correct, by going to that URL in safari and manually entering the credentials and I see the JSON. </p>
  
  <pre><code>@interface PlaylistData1b() &lt;NSURLSessionDataDelegate, NSURLSessionDelegate&gt;
  @property (nonatomic,strong) NSURLSession *session;
  @property (nonatomic, strong) NSString *requestString;
  @end
  
  @implementation PlaylistData1b
  
  - (instancetype)initWithURL:(NSString *)urlString
  {
      self = [super init];
      if(self){
          _requestString = urlString;
      }
      return self;
  }
  -(void)log
  {
      NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
      _session = [NSURLSession sessionWithConfiguration:config
                                               delegate:self
                                          delegateQueue:nil];
      [self fetchData];
  }
  
  -(void)fetchData
  {
      NSString *requestString = _requestString;
      NSURL *url = [NSURL URLWithString:requestString];
      NSURLRequest *req = [NSURLRequest requestWithURL:url];
  
      NSURLSessionDataTask *dataTask =
          [self.session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  
              NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
              NSLog(@"JSON: %@", jsonObject);
          }];
  
      [dataTask resume];
  }
  
  - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  {
      NSURLCredential *cred = [NSURLCredential credentialWithUser:username
                                                         password:password
                                                      persistence:NSURLCredentialPersistenceNone];
      [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
      completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
      NSLog(@"Finished Challenge");
  }
  </code></pre>
  
  <p>and here is my output.</p>
  
  <pre><code>2015-10-12 15:03:57.322 GetPlaylistData[7040:138551] Finished Challenge
  2015-10-12 15:04:33.321 GetPlaylistData[7040:138788] JSON: (null)
  </code></pre>
  
  <p>Any help is appreciated. Thanks.</p>