【问题标题】:Passing POST data from Objective-C to PHP将 POST 数据从 Objective-C 传递到 PHP
【发布时间】:2018-01-06 07:32:00
【问题描述】:

我正在尝试将一些 POST 数据从 Objective-c 传递到 PHP,但 PHP 文件似乎没有获取数据。

这是我发送它的方式:

- (void) sendJSONData:(NSDictionary *)dictData {

    NSError *error;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:kRootWebService];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];
    NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
                             @"IOS TYPE", @"typemap",
                             nil];
    NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
    [request setHTTPBody:postData];

    NSLog(@" URL: %@", request);
    NSLog(@" Body: %@", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;
        NSLog(@"%@", httpResponse.allHeaderFields);
        if (httpResponse.statusCode == 200) {

            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"This is my print out of data to string\n%@",str);

            //deseriealize the return
            id JSONObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

            NSDictionary* dictJSON;
            NSArray* arrJSON;

            NSLog(@"%@", dictJSON);

        } else {

            NSLog(@"There was an error connecting with the server, the status code returned was %i", (int)httpResponse.statusCode);

        }

    }];

    [postDataTask resume];


}

这是URL(URL正确)和Body的日志:

URL: http://xxxxxxxx.com/xxxxxx.php }
2017-07-30 15:20:10.602 MirrorBox[89680:5646406]  Body: {"name":"TEST IOS","typemap":"IOS TYPE"}

这是请求标头的日志

2017-07-30 15:20:10.751 MirrorBox[89680:5646478] {
    Age = 0;
    Connection = "keep-alive";
    "Content-Length" = 34;
    "Content-Type" = "text/html";
    Date = "Sun, 30 Jul 2017 19:20:10 GMT";
    Server = "Apache/2";
    "X-Powered-By" = "PHP/5.5.22";
}

这是返回数据的日志,错误信息是我自己的:

This is my print out of data to string
{"key":"could not read POST data"}

这里是 PHP 文件:

<?php

    if (!$_POST['IOS_TYPE']) { 
        echo json_encode(array("key" => "could not read POST data"));
    } else { 
        echo json_encode(array("key" => "returned string"));
    }


?>

【问题讨论】:

    标签: php ios json post


    【解决方案1】:

    如果您使用密钥 .. 传递 POST,您应该使用相同的密钥访问

     <?php
    
       if (!$_POST['typemap']) { 
          echo json_encode(array("typemap" => "could not read POST data"));
       } else { 
           echo json_encode(array("typemap" => "returned string"));
       }
    
    
    ?>
    

    或更好

      if (isset($_POST['typemap'])){
         if ($_POST['typemap'] == 'IOS TYPE' ) {
              echo 'IOS TYPE type in typemap POST';
         }
     }
      .....
    

    【讨论】:

    • 我应该提到我之前有过,并认为我可能正在向后读取键,但我按照你的回答这样做,我仍然没有点击 $_POST 数据
    • 这是一个空数组
    • 这意味着您没有在 POST 中发送值
    【解决方案2】:

    由于您在请求正文中传递 JSON,请尝试以下方式:

     $content = file_get_contents('php://input');
     $obj     = json_decode($content , false);      // decode to stdObj
     $typemap = $obj->typemap;
    

    或者如果您更喜欢使用关联数组:

     $ary     = json_decode($content , true);      // decode to array
     $typemap = $ary['typemap'];
    

    【讨论】:

    • 谢谢,这正是我所需要的。
    • 我很高兴...而且,不要盲目地工作 PHP,使用好的 IDE 工作!
    • 我正在编写一个 iOS 应用程序,只需要能够将用户设置存储到后端。自从我编写任何 PHP 以来已经有好几年了,我显然已经生疏了。我正在 Coda 中编写该代码,因此我应该更多地研究它以进行调试。
    猜你喜欢
    • 2010-11-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2014-03-15
    • 2013-08-30
    相关资源
    最近更新 更多