iPhone开发【十五】多线程开发之NSThread——异步下载图片
发布日期:2021-09-28 18:46:30 浏览次数:12 分类:技术文章

本文共 4201 字,大约阅读时间需要 14 分钟。

转载请注明出处,原文网址:  作者:张燕广

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

关键词:多线程 NSThread 等待框

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

[cpp] 
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface ViewController : UIViewController<NSURLConnectionDelegate>  
  4.   
  5. @property(strong,nonatomic)UIImageView *imageView;  
  6. @property(strong,nonatomic)NSMutableData *buffer;  
  7. @property Boolean done;  
  8. @end  

ViewController.m如下:

[cpp] 
  1. #import "ViewController.h"  
  2. @implementation ViewController  
  3. @synthesize imageView;  
  4. @synthesize buffer;  
  5. @synthesize done;  
  6.   
  7. -(void)loadView{  
  8.     //初始化视图  
  9.     [self initViews];  
  10.       
  11.     NSString *url = @"http://avatar.csdn.net/4/D/5/1_m_changgong.jpg";  
  12.     //在子线程执行图片下载操作  
  13.     [NSThread detachNewThreadSelector:@selector(downloadAppImage:) toTarget:self withObject:url];  
  14. }  
  15.   
  16. //初始化视图组件  
  17. -(void)initViews{  
  18.     CGRect frame = [UIScreen mainScreen].applicationFrame;  
  19.     imageView = [[UIImageView alloc]initWithFrame:frame];  
  20.     self.view = imageView;  
  21.     [self.view setBackgroundColor:[UIColor whiteColor]];  
  22. }  
  23.   
  24. //下载图片  
  25. -(void)downloadAppImage:(NSString *) url{  
  26.     //展示等待框  
  27.     [self showWaiting];  
  28.       
  29.     done = NO;  
  30.     //初始化缓冲区  
  31.     buffer = [NSMutableData data];  
  32.     [[NSURLCache sharedURLCache] removeAllCachedResponses];  
  33.     //设置请求及连接  
  34.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];  
  35.     NSURLConnection *connnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];  
  36.     if(connnection!=nil){  
  37.         while(!done){  
  38.              //NSLog(@"doing..");  
  39.             [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];  
  40.         }  
  41.     }  
  42.     //生成UIImage实例  
  43.     UIImage *img = [UIImage imageWithData:buffer];  
  44.     //通知主线程  
  45.     [self performSelectorOnMainThread:@selector(showImage:) withObject:img waitUntilDone:NO];   
  46.       
  47.     request = nil;  
  48.     connnection = nil;  
  49. }  
  50.   
  51. //填充图片  
  52. -(void)showImage:(UIImage *)img{    
  53.     [self.imageView setImage:img];  
  54.       
  55.     //关闭等待框  
  56.     [self hiddenWaiting];  
  57. }  
  58.   
  59. -(void)httpConnectEnd{  
  60.     NSLog(@"httpConnectEnd");  
  61. }  
  62.   
  63. -(void)httpConnectEndWithError{  
  64.     [self hiddenWaiting];  
  65.       
  66.     NSLog(@"httpConnectEndWithError");  
  67. }  
  68.   
  69. //展示等待框  
  70. -(void)showWaiting{  
  71.     int width = 32;  
  72.     int height = 32;  
  73.     CGRect frame = CGRectMake(0, -20, 320, 480);  
  74.     int x = frame.size.width;  
  75.     int y = frame.size.height;  
  76.     NSLog(@"x=%d,y=%d",x,y);  
  77.       
  78.     frame = CGRectMake((x-width)/2, (y-height)/2, width, height);  
  79.     UIActivityIndicatorView *progressInd = [[UIActivityIndicatorView alloc]initWithFrame:frame];  
  80.     [progressInd startAnimating];  
  81.     progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;  
  82.       
  83.     frame = CGRectMake((x-70)/2, (y-height)/2+height, 80, 20);  
  84.     UILabel *waitinglabel = [[UILabel alloc]initWithFrame:frame];  
  85.     waitinglabel.text = @"正在下载应用程序图片...";  
  86.     waitinglabel.textColor = [UIColor redColor];  
  87.     waitinglabel.font = [UIFont systemFontOfSize:15];  
  88.     waitinglabel.backgroundColor = [UIColor clearColor];  
  89.       
  90.     frame = CGRectMake(0, -20, 320, 480);  
  91.     UIView *waitingView = [[UIView alloc]initWithFrame:frame];  
  92.     waitingView.backgroundColor = [UIColor blackColor];  
  93.     waitingView.alpha = 0.7;  
  94.       
  95.     [waitingView addSubview:progressInd];  
  96.     [waitingView addSubview:waitinglabel];  
  97.       
  98.     [waitingView setTag:110];//设置tag  
  99.     [self.view addSubview:waitingView];  
  100. }  
  101.   
  102. //隐藏等待框  
  103. -(void)hiddenWaiting{  
  104.     //根据tag找到waitingView  
  105.     [[self.view viewWithTag:110]removeFromSuperview];  
  106. }  
  107.   
  108.   
  109. - (void)viewDidUnload  
  110. {  
  111.     [super viewDidUnload];  
  112.     // Release any retained subviews of the main view.  
  113. }  
  114.   
  115. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  116. {  
  117.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  118. }  
  119.   
  120. #pragma mark NSURLConnection Delegate methods  
  121. //不执行缓存  
  122. -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{  
  123.     return nil;  
  124. }  
  125.   
  126. //连接发生错误  
  127. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{  
  128.     [self performSelectorOnMainThread:@selector(httpConnectEndWithError) withObject:self waitUntilDone:NO];  
  129.     [buffer setLength:0];  
  130. }  
  131.   
  132. //接收数据  
  133. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{  
  134.     [buffer appendData:data];  
  135. }  
  136.   
  137. //下载完毕  
  138. -(void)connectionDidFinishLoading:(NSURLConnection *)connection{  
  139.     //NSLog(@"connectionDidFinishLoading");  
  140.     [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];   
  141.     //self.done = YES;  
  142. }  
  143.   
  144. @end  

2、运行效果如下:

转载地址:https://blog.csdn.net/h3c4lenovo/article/details/8563865 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:iPhone开发【十六】实现点击一个UIImageView时打开键盘
下一篇:iPhone开发【十四】多线程开发之NSThread——子线程模拟耗时操作

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年03月22日 12时02分20秒