douniao7308 2014-08-04 09:14
浏览 56
已采纳

将iOS字符串发送到PHP

I am trying to make an iPhone app send a string to my web server. At the moment when I print out $_POST in my php, the array is empty.

This is what I am currently trying;

    //NSString *query = @"SELECT name FROM users";
    NSString *query = @"select=name&from=users";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/www/service.php"]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[query dataUsingEncoding:NSUTF8StringEncoding]];

    [NSURLConnection connectionWithRequest:request delegate:self];

In the php script I simply do print_r($_POST); I get no error messages, only an empty array. What am I doing wrong? I have tried accessing the two fields separately and it does't work either ($POST['select'];)

  • 写回答

2条回答 默认 最新

  • duanfuxing2212 2014-08-07 08:02
    关注

    When you say that print_r prints out an empty array, do you mean that it prints it out an empty array in the browser? If that is the case, don't be concerned - it is not meant to print anything. I was working on something similar and realized that I was debugging it the wrong way.

    When you run your simulator in xcode, your php script will get called and $_POST will have a value. If you print_r at that moment it will temporarily hold the value of your two fields (but there is no way to see this on your browser). If you add some NSLogs and print out the response in xcode, you will see that the array is NOT empty.

    What I am trying to say is - the only way you should be debugging this should be in xcode, do not look at your browser.

    Try this to see your response in the log (this was previously posted - see the link in your first comment);

        NSError *err;
        NSURLResponse *response;
    
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request      returningResponse:&response error:&err];
    
        NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
    
        //This is for Response
        NSLog(@"got response==%@", resSrt);
    
        if(resSrt)
        {
            NSLog(@"got response");
        }
        else
        {
            NSLog(@"faield to connect");
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3