title: NSURLSessionDownloadTaskDelegate JSON response
body: <p>I am running a background NSURLSession session and i am trying to figure out a way to get the JSON response out of one of the NSURLDownloadTaskDelegate callbacks. I have configured my session to accept JSON responses.</p>
  
  <pre><code>NSURLSessionConfiguration *backgroundSession = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.Att.Locker.BackgroundUpload"];
  backgroundSession.HTTPAdditionalHeaders = @{ @"Accept":@"application/json"};
  session = [NSURLSession sessionWithConfiguration:backgroundSession delegate:uploader delegateQueue:nil];
  </code></pre>
  
  <p>I can easily parse JSON response for NSURLSessionDownloadTasks using the following callback. It writes the JSON response onto the sandbox in the form of NSURL.</p>
  
  <pre><code>- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location  {
  
    //Reading the Json response from the sandbox using the NSURL parameter
  }
  </code></pre>
  
  <p>My problem is if i encounter an error the callback above is not called, it seems to only get invoked in case of a successful download. Since i am using a background session i cannot use any of the NSURLSessionDataDelegate callbacks. I can only use the NSURLSessionDownloadTaskDelegate and NSURLSessionTaskDelegate and while i can get the task response using the following callback. I don't see the JSON in the response.</p>
  
  <pre><code>- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
  
  
  NSHTTPURLResponse *response = (NSHTTPURLResponse *)downloadTask.response;
  NSDictionary *httpResponse = [response allHeaderFields];
  
  NSLog(@"Response Header Fields:%@",[httpResponse allKeys]);
  }
  </code></pre>
  
  <p><strong>NSURLConnection</strong> has a <strong><em>didReceiveData</em></strong> parameter which gives us an <strong>NSData</strong> object which we can use to get the JSON response. I don't see that in the delegate callbacks for <strong>NSURLSession</strong> except for <strong>NSURLDataTask</strong> but we cant use data tasks in the background so how are we supposed to get the JSON response out ? Any help is appreciated</p>
  
  <p>EDIT:</p>
  
  <p>I usually experience this issue while i am running the app in the background (mostly when it is kicked out memory and not just suspended). I have implemented the callbacks in the appDelegate and i am able to re associate with the session.I think didFinishDownloadingToURL is only invoked in case of successful completion of a task but when a task fails there is no <em>guarantee</em> its going to be called but on the other hand didCompleteWithError gets called every time there is a failure </p>