NSURLConnection 下载数据 -- IOS(实例)
2012-11-03 19:15
309 查看
iPhone网络开发中如何使用NSURLConnection是本文要介绍的内容,这篇文章是翻译的苹果官方文档,想要看英文原版的可以到苹果网站查看,来看详细内容。
NSURLConnection 提供了很多灵活的方法下载URL内容也提供了一个简单的接口去创建和放弃连接,同时使用很多的delegate方法去支持连接过程的反馈和控制
如何创建一个连接呢?
为了下载url的内容,程序需要提供一个delegate对象,并且至少实现下面的方法
C代码
- (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请求
C代码
+ (NSData *)sendSynchronousRequest: (NSURLRequest *)request returningResponse: (NSURLResponse **)response error: (NSError **)error
1. request 要装载的URL请求. 这个request 对象 作为初始化进程的一部分,被深度复制(deep-copied). 在这个方法返回之后, 再修改request, 将不会影响用在装载的过程中的request
2. reponse 输出参数, 由服务器返回的URL响应
3. error 输出参数, 如果在处理请求的过程中发生错误,就会使用. 无错误,就为NULL
举例一
1、先创建一个NSURL
2、在通过NSURL创建NSURLRequest,可以指定缓存规则和超时时间
3、创建NSURLConnection实例,指定NSURLRequest和一个delegate对象
如果创建失败,则会返回nil,如果创建成功则创建一个NSMutalbeData的实例用来存储数据
代码:
C代码
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString:@“http://www.sina.com.cn/”]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConncetion=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if(theConnection)
{
//创建NSMutableData
receivedData=[[NSMutableData data] retain];
}else // 创建失败
C代码
NSURLRequestUseProtocolCachePolicy //NSURLRequest默认的cache policy, 是最能保持一致性的协议。
NSURLRequestReloadIgnoringCacheData //忽略缓存直接从原始地址下载
NSURLRequestReturnCacheDataElseLoad //只有在cache中不存在data时才从原始地址下载
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代码
-(void)connection:(NSURLConnection *) connectiondidReceiveResponse:
(NSURLResponse*)response
{
[receiveData setLength:0];
}
当下载开始的时候,每当有数据接收,代理会定期收到connection:didReceiveData:消息代理应当在实现中储存新接收的数据,下面的例子既是如此
C代码
-(void) connection:(NSURLConnection *) connection didReceiveData:
(NSData *) data
{
[receiveData appendData:data];
}
在上面的方法实现中,可以加入一个进度指示器,提示用户下载进度
当下载的过程中有错误发生的时候,代理会收到一个connection:didFailWithError消息,消息参数里面的NSError对象提供了具体的错误细节,它也能提供在用户信息字典里面失败的url请求(使用NSErrorFailingURLStringKey)
当代理接收到连接的connection:didFailWithError消息后,对于该连接不会在收到任何消息
举例
C代码
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[receivedData release];
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringErrorKey]);
}
最后,如果连接请求成功的下载,代理会接收connectionDidFinishLoading:消息代理不会收到其他的消息了,在消息的实现中,应该释放掉连接
举例:
C代码
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//do something with the data
NSLog(@"succeeded %d byte received",[receivedData length]);
[connection release];
[receivedData release];
}
一个实现异步get请求的例子:
C代码
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请求的例子:
C代码
// 初始化请求
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://mobile.51cto.com/iphone-281460.htm
http://blog.csdn.net/bl1988530/article/details/6590099
NSURLConnection 提供了很多灵活的方法下载URL内容也提供了一个简单的接口去创建和放弃连接,同时使用很多的delegate方法去支持连接过程的反馈和控制
如何创建一个连接呢?
为了下载url的内容,程序需要提供一个delegate对象,并且至少实现下面的方法
C代码
- (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请求
C代码
+ (NSData *)sendSynchronousRequest: (NSURLRequest *)request returningResponse: (NSURLResponse **)response error: (NSError **)error
1. request 要装载的URL请求. 这个request 对象 作为初始化进程的一部分,被深度复制(deep-copied). 在这个方法返回之后, 再修改request, 将不会影响用在装载的过程中的request
2. reponse 输出参数, 由服务器返回的URL响应
3. error 输出参数, 如果在处理请求的过程中发生错误,就会使用. 无错误,就为NULL
举例一
1、先创建一个NSURL
2、在通过NSURL创建NSURLRequest,可以指定缓存规则和超时时间
3、创建NSURLConnection实例,指定NSURLRequest和一个delegate对象
如果创建失败,则会返回nil,如果创建成功则创建一个NSMutalbeData的实例用来存储数据
代码:
C代码
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString:@“http://www.sina.com.cn/”]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConncetion=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if(theConnection)
{
//创建NSMutableData
receivedData=[[NSMutableData data] retain];
}else // 创建失败
C代码
NSURLRequestUseProtocolCachePolicy //NSURLRequest默认的cache policy, 是最能保持一致性的协议。
NSURLRequestReloadIgnoringCacheData //忽略缓存直接从原始地址下载
NSURLRequestReturnCacheDataElseLoad //只有在cache中不存在data时才从原始地址下载
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代码
-(void)connection:(NSURLConnection *) connectiondidReceiveResponse:
(NSURLResponse*)response
{
[receiveData setLength:0];
}
当下载开始的时候,每当有数据接收,代理会定期收到connection:didReceiveData:消息代理应当在实现中储存新接收的数据,下面的例子既是如此
C代码
-(void) connection:(NSURLConnection *) connection didReceiveData:
(NSData *) data
{
[receiveData appendData:data];
}
在上面的方法实现中,可以加入一个进度指示器,提示用户下载进度
当下载的过程中有错误发生的时候,代理会收到一个connection:didFailWithError消息,消息参数里面的NSError对象提供了具体的错误细节,它也能提供在用户信息字典里面失败的url请求(使用NSErrorFailingURLStringKey)
当代理接收到连接的connection:didFailWithError消息后,对于该连接不会在收到任何消息
举例
C代码
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[receivedData release];
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringErrorKey]);
}
最后,如果连接请求成功的下载,代理会接收connectionDidFinishLoading:消息代理不会收到其他的消息了,在消息的实现中,应该释放掉连接
举例:
C代码
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//do something with the data
NSLog(@"succeeded %d byte received",[receivedData length]);
[connection release];
[receivedData release];
}
一个实现异步get请求的例子:
C代码
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请求的例子:
C代码
// 初始化请求
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://mobile.51cto.com/iphone-281460.htm
http://blog.csdn.net/bl1988530/article/details/6590099
相关文章推荐
- NSURLConnection 下载数据 -- IOS(实例)
- NSURLConnection 下载数据 -- IOS(实例)
- NSURLConnection 下载数据 -- IOS(实例)
- NSURLConnection 下载数据 -- IOS
- iOS网络编程-iCloud键值数据存储编程实例
- TensorFlow学习笔记(二):实例数据下载
- iOS开发网络篇 一一 NSURLConnection-文件下载
- iOS之网络数据下载和JSON解析
- 三种方式使得iOS应用能够在后台进行数据更新和下载
- iOS网络编程-iCloud键值数据存储编程实例
- 三种方式使得iOS应用能够在后台进行数据更新和下载
- iOS异步下载图片实例代码
- IOS开发网络篇之使用NSConnection下载数据
- iOS 使用NSURLConnection连接服务器和JSON作为数据交换方式
- iOS开发 - 第04篇 - 网络 - 03 - 数据安全 & 文件下载
- IOS NSURLConnection(大文件下载)
- 三种方式使得iOS应用能够在后台进行数据更新和下载
- java 文件大数据Excel下载实例代码
- Java表格数据导出EXCEL 并从服务器下载实例
- iOS-使用NSURLConnection进行Http Get和Post请求网络数据