我最近在看一個關於NSURLConnection的蘋果示例,我試着將它實現到我的代碼中,但我不確定我是否正確地做。從網站檢索數據到iphone
基本上我想要連接到我的網站,我已經連接到一個php腳本,在我的數據庫中運行搜索,然後將它回顯給瀏覽器。我希望iPhone採取回顯的行並將其保存到字符串變量中。這是我的代碼。 這是否正確完成?
預先感謝您
NSString *stringToBeSent= [[NSString alloc] initWithFormat:
@"http:/xxxxx/siteSql.php? data=%@",theData];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString:stringToBeSent]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere... in my .h file
// NSMutableData *receivedData;
receivedData = [[NSMutableData data] retain];
//convert NSMutableData to a string
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog (@"result%@", receivedData);
} else {
// Inform the user that the connection failed.
NSLog(@"failed");
}
謝謝!想知道我需要在頭文件中聲明什麼委託方法?對於你上面提到的方法沒有被調用,因爲NSLog沒有出現在控制檯中。會接受! – Teddy13
你不聲明委託方法。確保你實現了所需的方法,即使它們只是shell而不做任何事情。所需的方法是連接:didReceiveResponse:,連接:didReceiveData :,連接:didFailWithError:和connectionDidFinishLoading :. – VsSoft
Big Nerd Ranch的iOS編程指南全面涵蓋了這個話題。您可以從http://www.bignerdranch.com/book/ios_programming_the_big_nerd_ranch_guide_nd_edition_上的書中下載這些解決方案。第26章在ListViewController .h/.m文件中顯示了這個解決方案的實現。我還建議購買這本書 - 這是一個非常好的閱讀! – VsSoft