I am trying to make an HTTP request from my iOS app to a PHP script in my server, sending POST data. The Objective-C code is the following:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mywebsite.com/script.php"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSMutableDictionary *info = [NSMutableDictionary dictionary];
[info setObject:[NSNumber numberWithInt:5] forKey:@"FIRST"];
[info setObject:[NSNumber numberWithInt:3] forKey:@"SECOND"];
NSData *data = [NSJSONSerialization dataWithJSONObject:info options:0 error:&error];
[request setHTTPBody:data];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"I GOT THE ANSWER: %@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
[postDataTask resume];
And this is the PHP script:
<?php
$first = intval($_POST["FIRST"]);
$second = intval($_POST["SECOND"]);
$result = $first + $second;
echo("= " . $result);
?>
The iOS app outputs
I GOT THE ANSWER: = 0
Which is incorrect. I'm not sure what the problem is.
I based my code on this solution: https://stackoverflow.com/a/19101084/555690. In that same question, the asker also posted another solution without using NSDictionary
, which does work for me, but I don't see why is this particular solution not working.