轉載請註明出處,原文網址:http://blog.csdn.net/m_changgong/article/details/8220819 作者:張燕廣
實現的功能:1)示範多線程NSThread開發;2)子線程中執行下載圖片工作,圖片下載完成前顯示等待框;
關鍵詞:多線程 NSThread 等待框
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
2、運行效果如下: