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];  
相关文章
相关标签/搜索