Trying to make simple post request to a remote PHP file. I'm not receiving the parameters on the server. Which I receive using Postman Btw. So the service seems ok. Something seems to be missing the iOS code here.
- (void) sendPostRequest {
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:baseURLPost];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:
@"JSON", @"responseType",
[UserManager sharedInstance].user.username, @"username",
self.textView.text, @"text",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
allowLossyConversion:YES];
[request setHTTPBody:postData];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", [error.userInfo valueForKey:@"NSDebugDescription"]);
} else {
NSArray *jsonResponseArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@", jsonResponseArray);
}
}] resume];
}
My PHP code to receive post REquest.
<?php
header("Content-type:application/json");
$postText= $_POST['text'];
$username = $_POST['username'];
$itemType = $_POST['itemType'];
$responseType = $_POST['responseType'];
$pictureLink = $_POST['pictureLink'];
$timestamp = $_POST['timestamp'];
$tags = $_POST['tags'];
if($timestamp==null){
$timestamp = date('Y-m-d G:i:s');
}
$arr = array('username' => $username);
echo json_encode($arr);
?>
The jsonResponseArray from this is username = "<null>";
Use
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
instead of $_POST
Like this:
<?php
header("Content-type:application/json");
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$arr = json_decode($jsonInput, true);
$postText= $arr['text'];
$username = $arr['username'];
$itemType = $arr['itemType'];
$responseType = $arr['responseType'];
$pictureLink = $arr['pictureLink'];
$timestamp = $arr['timestamp'];
$tags = $arr['tags'];
if($timestamp==null){
$timestamp = date('Y-m-d G:i:s');
}
$arr = array('username' => $username);
echo json_encode($arr);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With