注意:
self.allData 跟 _allData 在这个里面是一样的 但是涉及到内存管理 self.allData 会占用一次 retain retainCount会+1 而 _allData 不会
//.h
@interface ViewController :UIViewController<NSURLConnectionDataDelegate>
{
}
@property (retain,nonatomic) IBOutletUIImageView *viewImage;
@property(nonatomic,retain)NSMutableData *allData;
// .m
@implementation ViewController
- (void)viewDidLoad
{
[superviewDidLoad];
//http://z.abang.com/f/dslr/1/3/M/3/-/-/001.jpg
NSString *imageFile =@"http://sjrjy.apkzz.net/201009/17115639e6c12f45db3765.jpg";
NSURL *imageUrl = [NSURLURLWithString:imageFile];
NSURLRequest *requst = [NSURLRequestrequestWithURL:imageUrl];
//同步请求小数据量时候适合(只有这里执行且成功的收到数据才继续执行)
// NSData *data = [NSURLConnection sendSynchronousRequest:requst returningResponse:nil error:nil];
// if(data)
// {
// _viewImage.image = [UIImage imageWithData:data];
// //获取到xx.app 这个包
// NSBundle *bundle = [NSBundle mainBundle].bundlePath;
// NSString *filePath = [NSString stringWithFormat:@"%@/bundle.jpg",bundle];
// //存数据
// [data writeToFile:filePath atomically:YES];
//
// }
//异步请求 大数据量的情况
[NSURLConnectionconnectionWithRequest:requstdelegate:self];
}
#pragma mark -
//连接服务器得到响应时候回调该方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
self.allData = [[[NSMutableDataalloc]init]autorelease];
//获取数据总长度 进度条
// response.expectedContentLength
}
//收到数据时候回调该方法(一点一点的收到数据--》会被调用多次)
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//慢慢的收到数据 收集起来
[self.allDataappendData:data];
//当前数据长度
//self.allData.length
NSLog(@"didReceiveData");
}
//数据全部收到后回调
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
_viewImage.image = [UIImageimageWithData:self.allData];
NSLog(@"connectionDidFinishLoading");
}
//连接错误时候回调
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"connect fail ! error:%@",error);
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_viewImage release];
[_allDatarelease];
[superdealloc];
}
@end