您的位置:首页 > 产品设计 > UI/UE

NSURLRequest详解

2013-11-23 23:34 369 查看
URLRequest 的一个实例

// Create the request.
//所构建的NSURLRequest具有一个依赖于缓存响应的特定策略,cachePolicy取得策略,timeoutInterval
取得超时值
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                                          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.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
}


其中:

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请求的例子:

NSString *url = [NSString stringWithFormat:@"http://localhost/chat/messages.php?past=%ld&t=%ld",
                 lastId, time(0) ];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];

NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
    receivedData = [[NSMutableData data] retain];
}
else
{
}

- (void)timerCallback {
    //[timer release];
    [self getNewMessages];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (chatParser)
        [chatParser release];
    
    if ( messages == nil )
        messages = [[NSMutableArray alloc] init];
        
        chatParser = [[NSXMLParser alloc] initWithData:receivedData];
        [chatParser setDelegate:self];//set the delegate
    [chatParser parse];//start parse
    
    [receivedData release];
    
    [messageList reloadData];
    
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                                [self methodSignatureForSelector:
                                 @selector(timerCallback)]];
    [invocation setTarget:self];
    [invocation setSelector:@selector(timerCallback)];
    //timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:
    NO];
    [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];
    //if set yes,then very 5 seconds updata the table
}


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

// 初始化请求  
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];           
// 设置URL  
[request setURL:[NSURL URLWithString:urlStr]];  
// 设置HTTP方法  
[request setHTTPMethod:@"GET"];  
// 发 送同步请求, 这里得returnData就是返回得数据了  
NSData *returnData = [NSURLConnection sendSynchronousRequest:request   
                                           returningResponse:nil error:nil];   
// 释放对象  
[request release];


更多详细信息请参见苹果开发文档:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: