ViewController.h
1 #import2 3 @interface ViewController : UIViewController 4 5 { 6 UIImageView* imageView; 7 NSMutableData* imageData; 8 } 9 10 @end
ViewController.m
1 #import "ViewController.h" 2 3 @implementation ViewController 4 5 #pragma mark - viewDidLoad Event 6 -(void)initImageViewFData 7 { 8 imageData = [[NSMutableData alloc] init]; 9 imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 240)];10 [self.view addSubview:imageView];11 [imageView release];12 }13 -(void)startDownloadFImage14 {15 NSString* str = @"http://192.168.88.8/sns/my/headimage.php?uid=865";16 NSURL* url = [NSURL URLWithString:str];17 18 //建立一个请求,设置url,缓存,超时时间19 NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];20 //发送同步请求21 //NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];22 //异步请求23 [NSURLConnection connectionWithRequest:request delegate:self];24 //开始下载图片,什么时候知道下载完数据了25 }26 27 #pragma mark - viewDidLoad28 - (void)viewDidLoad29 {30 [super viewDidLoad];31 //初始.h里的字段32 [self initImageViewFData];33 //开始下载图片34 [self startDownloadFImage];35 }36 37 38 #pragma mark - NSURLConnectionDataDelegate39 //下载完响应头,准备下载内容40 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{41 [imageData setLength:0];42 [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;43 }44 //下载数据 , 多次调用45 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{46 //追加数据47 [imageData appendData:data];48 }49 //调用这个方法,证明下载完成50 - (void)connectionDidFinishLoading:(NSURLConnection *)connection{51 UIImage* image = [UIImage imageWithData:imageData];52 imageView.image = image;53 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;54 }55 //下载失败56 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{57 NSLog(@"下载失败");58 }