Search code examples
phpiosjsonasihttprequest

ASIHTTPRequest - Post JSON to PHP


I've used ASIHTTPRequest many times to post data to a php script in the past without any problems. This is my first time trying to send JSON and I can't get it to work.

NSError *error = nil;
NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithObjects:objectArray forKeys:keyArray];
[jsonDict setObject:email forKey:@"email"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];

NSURL *url = [NSURL URLWithString:@"http://192.168.1.12:8888/Folder/script.php"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"POST"];
[request appendPostData:jsonData];
[request addRequestHeader:@"Content-Type" value:@"application/json"];

[request setCompletionBlock:^{
    NSString *responseString = [request responseString];
    NSLog(@"finished text: %@", responseString);
}];

[request setFailedBlock:^{
    NSError *error = [request error];
    NSLog(@"failed: %@", error);
}];

[request startAsynchronous];

The PHP script right now is just

<?php print_r($_POST); ?>

which results in: Array (). Nothing is coming through. Any ideas what the problem could be?


Solution

  • It's not a problem with your Objective-C code but with your PHP script. See this answer. When sending data not as application/x-www-form-urlencoded you have to read the data from php://input.