My code in iOS:
NSString * some_str = @"{\"one\":\"two\",\"three\":\"four\"}";
NSData *objectData = [some_str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager POST:@"https://exmaple.com/post.php" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error);
}];
My code in backend (PHP):
<?php
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
echo $content;
// $responses = array();
header("Content-type: application/json, charset=utf-8");
// echo json_encode($responses);
$conn->close();
?>
If I echo $content, the response received by iOS will be some hex number. i.e. 3c21444f 43545950 (hex number for the json string start from the tail to the head connected by a "&" sign, i.e. three=four&one=two). If I echo $decoded, it returns an empty json.
And if I try to decode the json received by Post request, it failed. I believed that the received object was a possible input for json_decode function.
Should I rewrite my iOS code or PHP code or both?