NSURLConnection 用法

iPhone網絡開發中如何使用NSURLConnection是本文要介紹的內容,這篇文章是翻譯的蘋果官方文檔,想要看英文原版的能夠到蘋果網站查看,來看詳細內容。 javascript

 

NSURLConnection 提供了不少靈活的方法下載URL內容也提供了一個簡單的接口去建立和放棄鏈接,同時使用不少的delegate方法去支持鏈接過程的反饋和控制 php

 

如何建立一個鏈接呢? java

 

爲了下載url的內容,程序須要提供一個delegate對象,而且至少實現下面的方法 緩存

C代碼    收藏代碼
  1. - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response  
  2. - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data  
  3. - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error  
  4. - (void)connectionDidFinishLoading:(NSURLConnection *)connection  

 

NSURLConnect還提供了一個方便的類方法(class method) : sendSynchronousRequest:returningResponse:error: 可用來 同步地加載一個URL請求 服務器

C代碼    收藏代碼
  1. + (NSData *)sendSynchronousRequest:    (NSURLRequest *)request      returningResponse:   (NSURLResponse **)response    error:  (NSError **)error  
 

1. request 要裝載的URL請求. 這個request 對象 做爲初始化進程的一部分,被深度複製(deep-copied). 在這個方法返回以後, 再修改request, 將不會影響用在裝載的過程當中的request 網絡

2. reponse 輸出參數, 由服務器返回的URL響應 app

3. error   輸出參數, 若是在處理請求的過程當中發生錯誤,就會使用.  無錯誤,就爲NULL 異步

 

舉例一 函數

 

一、先建立一個NSURL 網站

二、在經過NSURL建立NSURLRequest,能夠指定緩存規則和超時時間

三、建立NSURLConnection實例,指定NSURLRequest和一個delegate對象

 

若是建立失敗,則會返回nil,若是建立成功則建立一個NSMutalbeData的實例用來存儲數據

 

代碼:

C代碼    收藏代碼
  1. NSURLRequest *theRequest=[NSURLRequest requestWithURL:    
  2.                   [NSURL URLWithString:@「http://www.sina.com.cn/」]    
  3.                  cachePolicy:NSURLRequestUseProtocolCachePolicy    
  4.                  timeoutInterval:60.0];    
  5. NSURLConnection *theConncetion=[[NSURLConnection alloc]         
  6.                    initWithRequest:theRequest delegate:self];    
  7. if(theConnection)    
  8. {    
  9. //建立NSMutableData    
  10.   receivedData=[[NSMutableData data] retain];    
  11. }else // 建立失敗   

 

C代碼    收藏代碼
  1. NSURLRequestUseProtocolCachePolicy //NSURLRequest默認的cache policy, 是最能保持一致性的協議。  
  2. NSURLRequestReloadIgnoringCacheData  //忽略緩存直接從原始地址下載  
  3. NSURLRequestReturnCacheDataElseLoad  //只有在cache中不存在data時才從原始地址下載  
  4. NSURLRequestReturnCacheDataDontLoad  //容許app肯定是否要返回cache數據,若是使用這種協議當本地不存在response的時候,建立NSURLConnection or NSURLDownload實例時將會立刻返回nil;這相似於離線模式,沒有創建網絡鏈接;  
 

NSURLConnection還有幾個初始化函數,有個初始化函數能夠作到建立鏈接可是並不立刻開始下載,而是經過start:開始

 

當收到initWithRequest: delegate: 消息時,下載會當即開始,在代理(delegate)收到connectionDidFinishLoading:或者 connection:didFailWithError:消息以前能夠經過給鏈接發送一個cancel:消息來中斷下載。

 

當服務器提供了足夠客戶程序建立NSURLResponse對象的信息時,代理對象會收到一個connection:didReceiveResponse:消息,在消息內能夠檢查NSURLResponse對象和肯定數據的預期長途,mime類型,文件名以及其餘服務器提供的元信息

 

要注意,一個簡單的鏈接也可能會收到多個connection:didReceiveResponse:消息當服務器鏈接重置或者一些罕見的緣由(好比多組mime文檔),代理都會收到該消息這時候應該重置進度指示,丟棄以前接收的數據

C代碼    收藏代碼
  1. -(void)connection:(NSURLConnection *) connectiondidReceiveResponse:    
  2.                         (NSURLResponse*)response    
  3. {   
  4.    [receiveData setLength:0];    
  5. }  
 

當下載開始的時候,每當有數據接收,代理會按期收到connection:didReceiveData:消息代理應當在實現中儲存新接收的數據,下面的例子既是如此

C代碼    收藏代碼
  1. -(void) connection:(NSURLConnection *) connection didReceiveData:    
  2.             (NSData *) data    
  3. {    
  4.    [receiveData appendData:data];    
  5.   
  6. }   
 

在上面的方法實現中,能夠加入一個進度指示器,提示用戶下載進度

 

當下載的過程當中有錯誤發生的時候,代理會收到一個connection:didFailWithError消息,消息參數裏面的NSError對象提供了具體的錯誤細節,它也能提供在用戶信息字典裏面失敗的url請求(使用NSErrorFailingURLStringKey)

 

當代理接收到鏈接的connection:didFailWithError消息後,對於該鏈接不會在收到任何消息

 

舉例

C代碼    收藏代碼
  1. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error    
  2. {   
  3. [connection release];    
  4.   
  5.   [receivedData release];    
  6.    NSLog(@"Connection failed! Error - %@ %@",    
  7.           [error localizedDescription],    
  8.           [[error userInfo] objectForKey:NSErrorFailingURLStringErrorKey]);    
  9. }  
 

最後,若是鏈接請求成功的下載,代理會接收connectionDidFinishLoading:消息代理不會收到其餘的消息了,在消息的實現中,應該釋放掉鏈接

 

舉例:

C代碼    收藏代碼
  1. -(void)connectionDidFinishLoading:(NSURLConnection *)connection    
  2. {  
  3.    //do something with the data    
  4.   NSLog(@"succeeded  %d byte received",[receivedData length]);   
  5.   
  6. [connection release];    
  7. [receivedData release];    
  8. }  
 

一個實現異步get請求的例子:

C代碼    收藏代碼
  1. NSString *url = [NSString stringWithFormat:@"http://localhost/chat/messages.php?past=%ld&t=%ld",  
  2.                      lastId, time(0) ];  
  3.       
  4.     NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
  5.     [request setURL:[NSURL URLWithString:url]];  
  6.     [request setHTTPMethod:@"GET"];  
  7.   
  8.     NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];    
  9.     if (conn)  
  10.     {    
  11.         receivedData = [[NSMutableData data] retain];    
  12.     }     
  13.     else     
  14.     {    
  15.     }   
  16.   
  17. - (void)timerCallback {  
  18.     //[timer release];  
  19.     [self getNewMessages];  
  20. }  
  21.   
  22. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response    
  23. {    
  24.     [receivedData setLength:0];    
  25. }    
  26.   
  27. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data    
  28. {    
  29.     [receivedData appendData:data];    
  30. }    
  31.   
  32. - (void)connectionDidFinishLoading:(NSURLConnection *)connection    
  33. {    
  34.     if (chatParser)  
  35.         [chatParser release];  
  36.       
  37.     if ( messages == nil )  
  38.         messages = [[NSMutableArray alloc] init];  
  39.   
  40.     chatParser = [[NSXMLParser alloc] initWithData:receivedData];  
  41.     [chatParser setDelegate:self];//set the delegate  
  42.     [chatParser parse];//start parse  
  43.   
  44.     [receivedData release];    
  45.       
  46.     [messageList reloadData];  
  47.       
  48.     NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:  
  49.                                     [self methodSignatureForSelector: @selector(timerCallback)]];  
  50.     [invocation setTarget:self];  
  51.     [invocation setSelector:@selector(timerCallback)];  
  52.     //timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];  
  53.     [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];//if set yes,then very 5 seconds updata the table  
  54. }   
 

一個實現同步Get請求的例子:

C代碼    收藏代碼
  1. // 初始化請求  
  2. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];           
  3. // 設置URL  
  4. [request setURL:[NSURL URLWithString:urlStr]];  
  5. // 設置HTTP方法  
  6. [request setHTTPMethod:@"GET"];  
  7. // 發 送同步請求, 這裏得returnData就是返回得數據了  
  8. NSData *returnData = [NSURLConnection sendSynchronousRequest:request   
  9.                                                returningResponse:nil error:nil];   
  10. // 釋放對象  
  11. [request release];  
相關文章
相關標籤/搜索