I am starting an NSURLSession background session and I am trying to figure out a way to get a JSON response from one of the NSURLDownloadTaskDelegate callbacks. I configured a session to receive JSON responses.
NSURLSessionConfiguration *backgroundSession = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.Att.Locker.BackgroundUpload"]; backgroundSession.HTTPAdditionalHeaders = @{ @"Accept":@"application/json"}; session = [NSURLSession sessionWithConfiguration:backgroundSession delegate:uploader delegateQueue:nil];
I can easily parse the JSON response for NSURLSessionDownloadTasks using the following callback. It writes the JSON response to the sandbox as NSURL.
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
My problem is that if I encounter an error, the call called above is not called, it seems to be called only if the download is successful. Since I am using a background session, I cannot use any calls to NSURLSessionDataDelegate. I can only use NSURLSessionDownloadTaskDelegate and NSURLSessionTaskDelegate, and so far I can get the task response using the following callback. I do not see JSON in the answer.
- (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]); }
NSURLConnection has a didReceiveData strong> parameter , which gives us an NSData strong> object, which we can use to get a JSON response. I donβt see that in the delegate callbacks for NSURLSession except NSURLDataTask , but we cannot use data tasks in the background, so how do we get the JSON response? Any help is appreciated
EDIT:
I usually experience this problem while I run the application in the background (mainly when it throws out the memory, and not just pauses). I implemented callbacks in appDelegate and I can associate with the session again. I think that didFinishDownloadingToURL is called only if the task completes successfully, but when the task is not completed, there is no guarantee that it will be called, but on the other hand didCompleteWithError is called every time a failure occurs