以下是代码,凝视也写得比較清楚:
头文件须要实现协议NSURLConnectionDelegate和NSURLConnectionDataDelegate
// // HttpDemo.h // MyAddressBook // // Created by hherima on 14-6-23. // Copyright (c) 2014年. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface HttpDemo : NSObject<NSURLConnectionDelegate, NSURLConnectionDataDelegate> { NSMutableData *receivedData; NSURLConnection *theConncetion; } @end
源文件
// // HttpDemo.m // MyAddressBook // // Created by hherima on 14-6-23. // Copyright (c) 2014年. All rights reserved. // #import "HttpDemo.h" @implementation HttpDemo /* NSURLConnection 提供了非常多灵活的方法下载URL内容,也提供了一个简单的接口去创建和放弃连接,同一时候使用非常多的delegate方法去支持连接过程的反馈和控制 举例: 1、先创建一个NSURL 2、再通过NSURL创建NSURLRequest,能够指定缓存规则和超时时间 3、创建NSURLConnection实例,指定NSURLRequest和一个delegate对象 假设创建失败,则会返回nil,假设创建成功则创建一个NSMutalbeData的实例用来存储数据 */ - (id)init { self = [super init]; // Override point for customization after application launch. NSURLRequest* theRequest = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.baidu.com"]// cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]; //当收到initWithRequest: delegate: 消息时,下载会马上開始,在代理(delegate) //收到connectionDidFinishLoading:或者connection:didFailWithError:消息之前 //能够通过给连接发送一个cancel:消息来中断下载 theConncetion=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if(theConncetion) { //创建NSMutableData receivedData = [NSMutableData data]; } else { //创建失败; } return self; } //当server提供了足够客户程序创建NSURLResponse对象的信息时。代理对象会收到一个connection:didReceiveResponse:消息。在消息内能够检查NSURLResponse对象和确定数据的预期长途,mime类型。文件名称以及其它server提供的元信息 //【要注意】,一个简单的连接也可能会收到多个connection:didReceiveResponse:消息当server连接重置或者一些罕见的原因(比方多组mime文档)。代理都会收到该消息这时候应该重置进度指示,丢弃之前接收的数据 -(void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse*)response { [receivedData setLength:0]; } //当下载開始的时候,每当有数据接收,代理会定期收到connection:didReceiveData:消息代理应当在实现中储存新接收的数据,以下的样例既是如此 -(void) connection:(NSURLConnection*)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } //当代理接收到连接的connection:didFailWithError消息后,对于该连接不会在收到不论什么消息 -(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error { theConncetion = nil; NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); } //数据完成下载,最后,假设连接请求成功的下载,代理会接收connectionDidFinishLoading:消息代理不会收到其它的消息了,在消息的实现中。应该释放掉连接 -(void)connectionDidFinishLoading:(NSURLConnection*)connection { //do something with the data NSString *s = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; NSLog(@"succeeded %@",s); theConncetion = nil; [receivedData setLength:0]; } @end