转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/8220819 作者:张燕广
实现的功能:1)演示多线程NSThread开发;2)子线程中执行下载图片工作,图片下载完成前显示等待框;
关键词:多线程 NSThread 等待框
1、新建视图控制器ViewController.m(不带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
2、运行效果如下: