NSURLRequest 简单的网络请求

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

NSURLRequest 简单的网络请求
- (void)viewDidLoad
{
    [super viewDidLoad];
     
    NSURL* url = [NSURL URLWithString:@"http://img21.mtime.cn/mg/2012/03/25/112544.76654880.jpg"];
    _imageData = [[NSMutableData alloc] init];
     
    //进度条
    _pv = [[UIProgressView alloc] initWithFrame:CGRectMake(50, 50, 220, 20)];
    [self.view addSubview:_pv];
    [_pv release];
     
     
    //创建一个请求
  //NSURLRequest* request = [NSURLRequest requestWithURL:url];
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    //发送请求
    [NSURLConnection connectionWithRequest:request delegate:self];
}
 
//接收响应头
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"接收到响应头");
    [_imageData setLength:0];
    //拿到响应体长度
    NSHTTPURLResponse* res = (NSHTTPURLResponse*)response;
    _length = [[res.allHeaderFields objectForKey:@"Content-Length"] floatValue];
    NSLog(@"length:%f",_length);
    //是否 开启 网络开关 状态栏的
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
 
//接收响应体,下载数据
/*
 0 1 2 3 4 5 6 7 8 9
 0 1
     2 3 4 
           5 6 7
                 8 9
 0 1 2 3 4 5 6 7 8 9
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"接收响应体");
    //把每次下载的数据添加到一起
    [_imageData appendData:data];
     
    //刷新进度条
    [_pv setProgress:_imageData.length / _length animated:YES];
}
 
//成功
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"成功");
    UIImage* image = [UIImage imageWithData:_imageData];
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
     
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
 
//失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"失败");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}