Search code examples
iosnsurlsessionnsurlsessionconfiguration

NSURLSessionConfiguration not accepting 'Content type' in HTTPAdditionalHeaders


I am making a REST web Service call using NSURLSession.I have set the content-Type for the webservice in NSURLSessionConfiguration.HTTPAdditionalHeaders. The below code was working absolutely fine in iOS 7.0 to iOS 8.1.3. But in iOS 8.3 the web service response data is returned as zero bytes when the content-Type is set in HTTPAdditionalHeaders.

Method 1:

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
NSData *postData = [dataToBeSent dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[urlRequest setHTTPBody:postData];
[urlRequest setHTTPShouldHandleCookies:YES];
[urlRequest setURL:urlOfService];
[urlRequest setHTTPMethod:@"POST"];

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @{@"Content-Type"       : @"application/json"};
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];

If I modify the above code to set the content-Type in NSMutableURLRequest as below, I receive data from webservice in iOS8.3. I am not sure what is causing this issue. Also I do not see anyone reporting this issue. I just want to know if my first way of calling the web service is a recommended way or am I doing anything wrong here? If the first method of calling the web service is wrong, why should it work on all other iOS versions except 8.3?

Method 2:

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
NSData *postData = [dataToBeSent dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[urlRequest setHTTPBody:postData];
[urlRequest setHTTPShouldHandleCookies:YES];
[urlRequest setURL:urlOfService];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];

Solution

  • You have to use the second method because of bug(feature?) in iOS 8.3 SDK http://openradar.appspot.com/20498383