php - 带有目标c的Xcode将json数据发布到php api
问题描述
我试图将一些用户数据从 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];
}
当前结果
{设备=iPhone;"device_type"="iPhone6"; 设备ID=f2cd64;fcmtoken="9exBTN7FSfg"; 键=XVoVjA;lat="2.90909862"; long="101.897877"; }
预期结果
{ “设备”:“iPhone”,“device_type”:“iPhone6”,“deviceid”:“f2cd64”,“fcmtoken”:“9exBTN7FSfg”,“key”:“XVoVjA”,“lat”:“2.90909862”,“长":"101.897877" }
解决方案
嗯,看起来很复杂。您正在将您的 jsonUserDictionary 嵌入到其他字典中,并且在您需要删除[]
...之后尝试这个简单的方法:
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: jsonUserDictionary options:NSJSONWritingPrettyPrinted error:&writeError];
if (writeError) {
NSLog(@"Write error : %@", [writeError description]);
}
NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] stringByRemovingPercentEncoding];
// now send this
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[resuest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// get rid of apple dogma
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
_urlConnection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
推荐阅读
- python - 带有 a. 的气流 Python 运算符。返回类型
- java - 将字符串数组转换为二维字符数组
- java - 如何调用在 catch 块中引发异常的方法?
- swift - NSTableView 的访问值
- arrays - python 数组第一个和第二个元素的紧凑形式
- node.js - webpack 4 react build 导致令牌错误,但运行启动有效
- maven - 在聚合器项目中为所有模块生成站点
- spring-boot - Spring Boot 2x 执行器 http 跟踪不跟踪主体
- java - 为什么元素不能位于硒的方法函数中?
- javascript - 如何保存 HTML 事件以供以后使用?