我试图将一些来自iOS的用户数据发布到我的php api,但是我接收的数据没有正确格式化为JSON文件。请有人帮我一下,因为我对IOS和目标C很陌生。
这是我的PHP示例
<?php
if(isset($_REQUEST['data']) ){
if(!empty($_REQUEST['data']) && strlen($_REQUEST['data']) > 3){
$api_data = $_REQUEST['data'];
$json_data = json_decode($api_data, true);
$hash_key = md5($api_data);
$post_var = array(
'date' => date('m-d-Y h:m:sA'),
);
$post_var = '{"apiData":'.$api_data.', "moreData":'.json_encode($post_var).'}';
$readTheApis = __DIR__ . '/cdn/api_request_note.txt';
$handl_log = fopen($readTheApis, "a+") or die("Failed to create log");
$addlog = fwrite($handl_log, $post_var. "\r\n");
fclose($handl_log);
foreach ($json_data as $key => $val) {
echo $key . ' | ' . $val;
}
}
}
目标C
-(void)HitAPI{
[SVProgressHUD showWithStatus:@"Wait.."];
NSDictionary *jsonUserDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
Str_LatPost, @"lat",
Str_LongPost, @"long",
[[FIRInstanceID instanceID] token], @"fcmtoken",
[[UIDevice currentDevice] name], @"device",
deviceName(), @"device_type",
[[NSUserDefaults standardUserDefaults] valueForKey:@"pref_mytoken"], @"deviceid",
@"FRaVY4cXVoVjA", @"key", nil];
NSMutableArray *mutArrData = [NSMutableArray array];
[mutArrData addObject:jsonUserDictionary];
NSString*StrPost = [NSString stringWithFormat:@"data=%@",mutArrData];
NSString *jsonString = StrPost;
jsonString = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"[" withString:@""];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"]" withString:@""];
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[
NSString stringWithFormat:@"https://example.com/app/1d54f4dax/api.php?data"
]]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
/*
BECUSE OF DEPRECIATE WARNING I ADDED THE BELOW CODE BUT AM NOT SURE IF IT WILL WORK
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];*/
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *theConnection = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
// do something with the data'
}];
[theConnection resume];
}
当前结果
device=iphone;“device_type”=“iphone6”;deviceid=f2cd64;
fcmtoken=“9exbtn7fsfg”;key=xvovja;lat=“2.90909862”;
long=“101.897877”;
预期结果
“device”:“iphone”,“device_type”:“iphone6”,“deviceid”:“f2cd64”,
“fcmtoken”:“9exbtn7fsfg”,“key”:“xvovja”,“lat”:“2.90909862”,
“long”:“101.897877”