2012-04-10 43 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