2012-09-13 67 views
2

我可以得到一些幫助嗎?我很絕望。我有一個PHP腳本,它發送參數,它執行一些處理,然後使用echo輸出結果。我用如何使用NSURLConnection獲取PHP回顯?

[[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"myPHPPathWithParameters"]] encoding:NSUTF8StringEncoding]; 

過去得到呼應PHP作爲的NSString的信息,和它的工作,但現在沒有。它返回一個NULL NSString。無論如何,我認爲正確的方法是通過實現NSURLConnection,因爲它實現了用於觀察連接進度的委託方法等。所以,我聲明瞭一個靜態NSMutableData * receivedData,然後我使用iOS文檔中的示例:

NSURLRequest *req=[NSURLRequest 
          requestWithURL:[NSURL URLWithString:@"http://myphp.php?parameters=paramteres"] 
          cachePolicy:NSURLRequestUseProtocolCachePolicy 
          timeoutInterval:30.0]; 

    NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:req delegate:self]; 

    if (con) 
     receivedData = [[NSMutableData data] retain]; 
    else 
     NSLog(@"Request failed to load."); 

然後,我實現委託方法(我也自我聲明NSURLConnectionDataDelegate):

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
    NSLog(@"RECEIVED DATA;"); 
    [receivedData appendData:data]; 
} 

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 
    NSLog(@"received response;"); 
    [receivedData setLength:0]; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
    NSLog(@"FINISHED;"); 
} 

但是這些方法永遠不會叫!終端永遠不會顯示任何日誌消息,顯示委託方法執行。據我瞭解,這個方法被調用,並將數據附加到receivedData,然後我必須從receiveData獲取NSString,一旦connectionDidFinishLoading方法被調用。有什麼建議麼?我也嘗試了NSURLConnection中的同步請求類方法,但該方法獲得了整體HTML,我只是想獲得什麼PHP回聲,並解析它作爲NSString在應用程序內部使用:(

回答

2

receivedData轉換成串

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
    NSString *myStringData = [[NSString alloc] initWithData:receivedData encoding:NSStringEncodingConversionAllowLossy]; 
} 

,然後打印您的字符串NSLog(@"MyString: %@", myStringData)

+0

但委託方法永遠不會叫!所以receivedData總是空。 – acib708