The problem is either (a) how you implemented the NSURLConnectionDataDelegate
methods; or (b) how your server processed the request.
On that first issue, because NSURLConnection
is deprecated anyway, we can use NSURLSession
, simplify your code, and eliminate the potential source of problem of the NSURLConnection
data source and delegate code:
NSError *encodeError;
NSDictionary *parameters = @{@"userId":@"733895",@"startDate":@"24-04-2016",@"endDate":@"25-04-2016"};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&encodeError]];
NSAssert(request.HTTPBody, @"Encoding failed: %@", error);
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"Network error: %@", error);
}
if (data == nil) {
return;
}
NSError *parseError;
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!responseObject) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"could not parse; responseString = %@", responseString);
return;
}
NSLog(@"Everything ok; responseObject = %@", responseObject);
}];
[task resume];
Note, I tidied up the building of the JSON request, too. More importantly, I'm also doing error handling, so if the JSON response can't be parsed, we can see why.
In terms of reasons why the response cannot be processed, there could be an issue in the web service code. For example, perhaps the web generates JSON response to application/x-www-form-urlencoded
requests. It could be many things. But without doing this logging, you will never know why it failed.
Note, in iOS 9, you need to tell your project that you're willing to accept insecure connections to your web service. So right-click on the info.plist
, "Open As" - "Source code" and then add the following to it:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>15.0.3.1</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>