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 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多