现在的位置: 首页 > 综合 > 正文

URLRequest 的一个实例

2013年09月09日 ⁄ 综合 ⁄ 共 6661字 ⁄ 字号 评论关闭

 

URLRequest 的一个实例

  1. // Create the request.  
  2. //所构建的NSURLRequest具有一个依赖于缓存响应的特定策略,cachePolicy取得策略,timeoutInterval取得超时值  
  3. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]  
  4.                         cachePolicy:NSURLRequestUseProtocolCachePolicy  
  5.                     timeoutInterval:60.0];  
  6. // create the connection with the request  
  7. // and start loading the data  
  8. NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];  
  9. if (theConnection) {  
  10.     // Create the NSMutableData to hold the received data.  
  11.     // receivedData is an instance variable declared elsewhere.  
  12.     receivedData = [[NSMutableData data] retain];  
  13. } else {  
  14.     // Inform the user that the connection failed.  
  15. }  

其中:

NSURLRequest默认的cache policy是NSURLRequestUseProtocolCachePolicy
是最能保持一致性的协议。
NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载
NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data时才从原始地址下载
NSURLRequestReturnCacheDataDontLoad 允许app确定是否要返回cache数据,如果使用这种协议当本地不存在response的时候,创建NSURLConnection
or NSURLDownload实例时将会马上返回nil;这类似于离线模式,没有建立网络连接;

你只需要实现以下delegate方法来处理数据响应

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

NSURLConnect还提供了一个方便的类方法(class method) : sendSynchronousRequest:returningResponse:error:可用来 同步地加载一个URL请求

+ (NSData *)sendSynchronousRequest:    (NSURLRequest *)request      returningResponse:   (NSURLResponse **)response    error:  (NSError **)error

  • request 要装载的URL请求. 这个request 对象 作为初始化进程的一部分,被深度复制(deep-copied). 在这个方法返回之后, 再修改request, 将不会影响用在装载的过程中的request
  • reponse 输出参数, 由服务器返回的URL响应
  • error   输出参数, 如果在处理请求的过程中发生错误,就会使用.  无错误,就为NULL
一个实现异步get请求的例子:
  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.   
  18. - (void)timerCallback {  
  19.     //[timer release];
      
  20.     [self getNewMessages];  
  21. }  
  22.   
  23. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response    
  24. {    
  25.     [receivedData setLength:0];    
  26. }    
  27.   
  28. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data    
  29. {    
  30.     [receivedData appendData:data];    
  31. }    
  32.   
  33. - (void)connectionDidFinishLoading:(NSURLConnection *)connection    
  34. {    
  35.     if (chatParser)  
  36.         [chatParser release];  
  37.       
  38.     if ( messages == nil )  
  39.         messages = [[NSMutableArray alloc] init];  
  40.   
  41.     chatParser = [[NSXMLParser alloc] initWithData:receivedData];  
  42.     [chatParser setDelegate:self];//set the delegate  
  43.     [chatParser parse];//start parse  
  44.   
  45.     [receivedData release];    
  46.       
  47.     [messageList reloadData];  
  48.       
  49.     NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:  
  50.                                     [self methodSignatureForSelector: @selector(timerCallback)]];  
  51.     [invocation setTarget:self];  
  52.     [invocation setSelector:@selector(timerCallback)];  
  53.     //timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];  
  54.     [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];//if set yes,then very 5 seconds updata the table  
  55. }   

一个实现同步Get请求的例子:

  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];  

更多详细信息请参见苹果开发文档:

抱歉!评论已关闭.