2012-04-10 41 views
0

我有一个应用程序发送数据到NSURLRequest和NSURLConnexion的PHP脚本。我想要的是使用post方法发送像“Hello world”这样的数据,并且我希望显示在我的应用程序“myPHPScript.php的Hello world!”中但我对Web服务没有经验,特别是PHP。从NSURLRequest的PHP脚本接收数据

这里是我的Objective-C代码,它发送请求:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL 

           URLWithString:@"http://localhost:8888/testNSURL/index.php"] 

           cachePolicy:NSURLRequestUseProtocolCachePolicy 

           timeoutInterval:60.0]; 

    [request setHTTPMethod:@"POST"]; 
    NSString *postString = @"myVariable=Hello world !"; 
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    if (theConnection) { 

     receiveData = [NSMutableData data]; 

} 

,这是我的PHP代码:

<?php 
if(isset($_REQUEST["myVariable"])) { 
    echo json_encode("Hello from index.php !"); 
} 
else echo json_encode('Request failed'); 
?> 

我的问题是:

  • 是我的PHP代码正确吗?
  • 如何在我的obj-c应用程序中捕获echo json_encode("Hello from index.php !");

回答

0

我个人使用ASIFormDataRequest时发布的东西到服务器。当你从这个方法获取信息回来你可以做这样的事情让已经回显服务器上所有的数据/字符串值:

- (void)requestFinished:(ASIHTTPRequest *)aRequest { 
    NSData *responseData = [aRequest responseData]; 
    NSString *responseString = [aRequest responseString]; 
} 

充分利用数据信息的字符串就像做所以:

[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding] 
+0

我用它,但我有很多错误的/有和没有ARC警告,这就是为什么我用的NSURLRequest/NSURLConnexion – Edelweiss 2012-04-10 13:09:34

+0

哦,从来没有真正有任何问题,它在所有..也许我可以帮你解决这些错误? – Manuel 2012-04-10 13:10:23

+0

我还添加了从nsdata获取字符串的方法:) – Manuel 2012-04-10 13:11:42