dsxxqndv41105 2018-06-16 16:28
浏览 70
已采纳

带有目标c的Xcode将json数据发布到php api

Am trying to post some user data from ios to my php api, but the data am receiving is not properly formatted as a json file. Please can someone help me out as i am very new to ios and objective c.

Here is my php sample

<?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. "
");
        fclose($handl_log);
        foreach ($json_data as $key => $val) {
            echo $key . ' | ' . $val;
        }
    }
}

OBJECTIVE 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];
}

Current result

{ device=iPhone; "device_type"="iPhone6"; deviceid=f2cd64; fcmtoken="9exBTN7FSfg"; key=XVoVjA; lat="2.90909862"; long="101.897877"; }

Expected Result

{ "device":"iPhone", "device_type":"iPhone6", "deviceid":"f2cd64", "fcmtoken":"9exBTN7FSfg", "key":"XVoVjA", "lat":"2.90909862", "long":"101.897877" }

  • 写回答

1条回答 默认 最新

  • drtoclr046994545 2018-06-16 17:47
    关注

    hmmm , seems complicated for naught. Your are embedding your jsonUserDictionary into some other dictionary, and after you need to remove the [] ... try this simple approach:

    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];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化