iPhone开发多线程开发之NSThread——异步下载图片 .

实现的功能:1)演示多线程NSThread开发;2)子线程中执行下载图片工作,图片下载完成前显示等待框;

关键词:多线程 NSThread 等待框


运行效果图:
[img]
[img]http://dl.iteye.com/upload/attachment/0078/7359/14ae2eae-5543-3c91-b72e-83b818723801.png[/img]
[/img]
[img]
[img]http://dl.iteye.com/upload/attachment/0078/7361/70cdd698-e5b4-3e56-a791-faa4b7bf5a95.png[/img]
[/img]


1、新建视图控制器ViewController(不带xib),作为根视图控制器,通过ViewController的-(void)loadView方法构建UI,ViewController.h如下:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLConnectionDelegate>

@property(strong,nonatomic)UIImageView *imageView;
@property(strong,nonatomic)NSMutableData *buffer;
@property Boolean done;
@end



ViewController.m如下:

#import "ViewController.h"
@implementation ViewController
@synthesize imageView;
@synthesize buffer;
@synthesize done;

-(void)loadView{
//初始化视图
[self initViews];

NSString *url = @"http://avatar.csdn.net/4/D/5/1_m_changgong.jpg";
//在子线程执行图片下载操作
[NSThread detachNewThreadSelector:@selector(downloadAppImage:) toTarget:self withObject:url];
}

//初始化视图组件
-(void)initViews{
CGRect frame = [UIScreen mainScreen].applicationFrame;
imageView = [[UIImageView alloc]initWithFrame:frame];
self.view = imageView;
[self.view setBackgroundColor:[UIColor whiteColor]];
}

//下载图片
-(void)downloadAppImage:(NSString *) url{
//展示等待框
[self showWaiting];

done = NO;
//初始化缓冲区
buffer = [NSMutableData data];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
//设置请求及连接
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLConnection *connnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connnection!=nil){
while(!done){
//NSLog(@"doing..");
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
//生成UIImage实例
UIImage *img = [UIImage imageWithData:buffer];
//通知主线程
[self performSelectorOnMainThread:@selector(showImage:) withObject:img waitUntilDone:NO];

request = nil;
connnection = nil;
}

//填充图片
-(void)showImage:(UIImage *)img{
[self.imageView setImage:img];

//关闭等待框
[self hiddenWaiting];
}

-(void)httpConnectEnd{
NSLog(@"httpConnectEnd");
}

-(void)httpConnectEndWithError{
[self hiddenWaiting];

NSLog(@"httpConnectEndWithError");
}

//展示等待框
-(void)showWaiting{
int width = 32;
int height = 32;
CGRect frame = CGRectMake(0, -20, 320, 480);
int x = frame.size.width;
int y = frame.size.height;
NSLog(@"x=%d,y=%d",x,y);

frame = CGRectMake((x-width)/2, (y-height)/2, width, height);
UIActivityIndicatorView *progressInd = [[UIActivityIndicatorView alloc]initWithFrame:frame];
[progressInd startAnimating];
progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;

frame = CGRectMake((x-70)/2, (y-height)/2+height, 80, 20);
UILabel *waitinglabel = [[UILabel alloc]initWithFrame:frame];
waitinglabel.text = @"正在下载应用程序图片...";
waitinglabel.textColor = [UIColor redColor];
waitinglabel.font = [UIFont systemFontOfSize:15];
waitinglabel.backgroundColor = [UIColor clearColor];

frame = CGRectMake(0, -20, 320, 480);
UIView *waitingView = [[UIView alloc]initWithFrame:frame];
waitingView.backgroundColor = [UIColor blackColor];
waitingView.alpha = 0.7;

[waitingView addSubview:progressInd];
[waitingView addSubview:waitinglabel];

[waitingView setTag:110];//设置tag
[self.view addSubview:waitingView];
}

//隐藏等待框
-(void)hiddenWaiting{
//根据tag找到waitingView
[[self.view viewWithTag:110]removeFromSuperview];
}


- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark NSURLConnection Delegate methods
//不执行缓存
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
return nil;
}

//连接发生错误
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self performSelectorOnMainThread:@selector(httpConnectEndWithError) withObject:self waitUntilDone:NO];
[buffer setLength:0];
}

//接收数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[buffer appendData:data];
}

//下载完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//NSLog(@"connectionDidFinishLoading");
[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
//self.done = YES;
}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值