2012-01-22 98 views
0

我最近在看一個關於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"); 

     } 

回答

1

我想你可能會錯過了兩件事情:

  1. 在該方法中,你使用觸發檢索數據請確保您釋放舊數據初始化之前:

    [retrievedData release]; 
    retrievedData=[[NSMutableData alloc] init]; 
    
  2. 我假設空間是一個錯字或東西f或網址?

  3. 您無需致電requestWithURL:cachePolicy:timeoutInterval:requestWithURL:使用與您所選的相同的默認值。

  4. 數據將以塊形式出現。你必須處理隨着時間的推移,這種方法外,利用委託方法connection:didReceiveData:,像這樣:

    - (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data 
    { 
        [receivedData appendData:data]; 
    } 
    
  5. 同樣,如果你想要的東西與數據一旦它的所有接收完成後,你做它connectionDidFinishLoading:注意,連接被釋放,因此它在你的頭被定義爲一個實例變量(如:NSURLConnection *connection;

    - (void)connectionDidFinishLoading:(NSURLConnection *)conn 
    { 
        NSString *stringData= [[NSString alloc] 
        initWithData:receivedData encoding:NSUTF8StringEncoding]; 
        NSLog(@"Got data? %@", stringData); 
        [connection release]; 
        connection = nil; 
        // Do unbelievably cool stuff here // 
    } 
    
  6. 還應考慮其他委託方法像connection:didFailWithError:你可能想釋放連接和StringData是那裏也是出現錯誤的情況。

我希望這有些幫助!請享用!

+0

謝謝!想知道我需要在頭文件中聲明什麼委託方法?對於你上面提到的方法沒有被調用,因爲NSLog沒有出現在控制檯中。會接受! – Teddy13

+0

你不聲明委託方法。確保你實現了所需的方法,即使它們只是shell而不做任何事情。所需的方法是連接:didReceiveResponse:,連接:didReceiveData :,連接:didFailWithError:和connectionDidFinishLoading :. – VsSoft

+0

Big Nerd Ranch的iOS編程指南全面涵蓋了這個話題。您可以從http://www.bignerdranch.com/book/ios_programming_the_big_nerd_ranch_guide_nd_edition_上的書中下載這些解決方案。第26章在ListViewController .h/.m文件中顯示了這個解決方案的實現。我還建議購買這本書 - 這是一個非常好的閱讀! – VsSoft