首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用目标c的Xcode将json数据发布到php api。

使用目标c的Xcode将json数据发布到php api。
EN

Stack Overflow用户
提问于 2018-06-17 00:28:49
回答 1查看 147关注 0票数 0

我试图从ios发布一些用户数据到我的php api,但收到的数据没有正确格式化为json文件。有人能帮帮我吗?因为我对ios和objective c非常陌生。

这是我的php示例

代码语言:javascript
复制
<?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;
        }
    }
}

OBJECTIVE C

代码语言:javascript
复制
-(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“}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-17 01:47:05

嗯,似乎没有什么复杂的东西。您正在将您的jsonUserDictionary嵌入到其他字典中,并且在您需要删除[]之后...试试这个简单的方法:

代码语言:javascript
复制
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];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50889678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档