外面给
1. 网址
2. 请求方式
3. post 请求体的字符串
里面封
1.请求对象
2. 链接对象
3. 代理方法
#import <UIKit/UIKit.h>
@interface ThreeViewController : UIViewController
// 显示图片
@property (nonatomic, retain) UIImageView *imageView;
// 显示加载进度
@property (nonatomic, retain) UILabel *label;
// 异步拼接数据
@property (nonatomic, retain) NSMutableData *data;
// 声明一个链接
@property (nonatomic ,retain) NSURLConnection *connection;
// 定义一个接收图片的总大小
@property (nonatomic, assign) long long totallLength;
@end
- (void)dealloc
{
// 终止请求
[_connection cancel];
[_imageView release];
[_label release];
[_data release];
[_connection release];
[super dealloc];
}
- (void)viewDidLoad {
[self addSubview];
[self setUpDataGET];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
// 布局
- (void)addSubview
{
self.imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
// self.imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.imageView];
[_imageView release];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(25, 70, 150, 30)];
// self.label.backgroundColor = [UIColor blueColor];
[self.view addSubview:self.label];
[_label release];
}
// 请求选用什么方法 get代理实现异步请求
- (void)setUpDataGET
{
NSURL *url = [NSURL URLWithString:kImageURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:@"GET"];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
[self.connection start];
}
#pragma mark - 实现协议里面的方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"加载失败");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.data appendData:data];
// 利用data 加载图片
_imageView.image = [UIImage imageWithData:self.data];
// 计算图片加载进度
_label.text = [NSString stringWithFormat:@"%.0f%%",1.0 * self.data.length / self.totallLength * 100];
NSLog(@"一点点加载数据");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 获取图片大小
self.totallLength = response.expectedContentLength ;
self.data = [NSMutableData data];
NSLog(@"返回数据源");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:(self.data) options:(NSJSONReadingMutableContainers) error:nil];
// NSLog(@"%@", dataDic);
NSLog(@"完成加载");
}
效果图