现在的位置: 首页 > 综合 > 正文

iPhone开发【十七】多线程开发之NSOperation&NSOperationQueue——异步下载图片

2013年05月19日 ⁄ 综合 ⁄ 共 3978字 ⁄ 字号 评论关闭

转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/8238093 作者:张燕广

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

关键词:多线程 NSOperation NSOperationQueue 等待框

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

2、新建继承自NSOperation且实现协议NSURLConnectionDelegate的类DownLoadImageTask,DownLoadImageTask.h如下:

  1. #import <Foundation/Foundation.h>  
  2. @protocol DownLoadImageDelegate;  
  3.   
  4. @interface DownLoadImageTask : NSOperation<NSURLConnectionDelegate>{  
  5.     int operationId;  
  6.     long long totalLength;  
  7.     BOOL done;  
  8. }  
  9. @property int operationId;  
  10. @property(nonatomic,assign) id<DownLoadImageDelegate>downloadImageDelegate;  
  11. @property(nonatomic,retain) NSMutableData *buffer;  
  12. @property(nonatomic,retain) NSURLRequest *request;  
  13. @property(nonatomic,retain) NSURLConnection *connection;  
  14.   
  15. - (id)initWithURLString:(NSString *)url;  
  16. @end  
  17.   
  18.   
  19. @protocol DownLoadImageDelegate  
  20. //图片下载完成的委托  
  21. -(void)imageDownLoadFinished:(UIImage *)img;  
  22. //更新图片下载进度条的值  
  23. -(void)updateDownProgress:(double) value;  
  24. @end  

DownLoadImageTask.m如下:

  1. <span style="font-family:Microsoft YaHei;font-size:18px;">#import "DownLoadImageTask.h"  
  2.   
  3. @implementation DownLoadImageTask  
  4. @synthesize operationId;  
  5. @synthesize downloadImageDelegate;  
  6. @synthesize buffer;  
  7. @synthesize request;  
  8. @synthesize connection;  
  9.   
  10. - (id)initWithURLString:(NSString *)url{  
  11.     NSLog(@"url=%@",url);  
  12.     self = [super init];  
  13.     if(self){  
  14.         request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];  
  15.         buffer = [NSMutableData data];  
  16.     }  
  17.     return self;  
  18. }  
  19.   
  20. //主要处理方法  
  21. -(void)start{ //或者main  
  22.     NSLog(@"DownLoadImageTask-start");  
  23.       
  24.     if(![self isCancelled]){  
  25.         //暂停一下  
  26.         [NSThread sleepForTimeInterval:1];  
  27.         //设置connection及其代理  
  28.         connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];  
  29.         if(connection!=nil){  
  30.             while(!done){  
  31.                 [[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];  
  32.             }  
  33.         }  
  34.     }  
  35. }  
  36.   
  37. -(void)httpConnectEndWithError{  
  38.     //[self hiddenWaiting];  
  39.     NSLog(@"httpConnectEndWithError");  
  40. }  
  41.   
  42. -(void)dealloc{  
  43.     buffer = nil;  
  44.     connection = nil;  
  45.     request = nil;  
  46.     downloadImageDelegate = nil;  
  47. }  
  48.   
  49. #pragma NSURLConnection delegate methods  
  50. //不执行缓存  
  51. -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{  
  52.     return nil;  
  53. }  
  54.   
  55. //连接发生错误  
  56. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{  
  57.     [self performSelectorOnMainThread:@selector(httpConnectEndWithError) withObject:self waitUntilDone:NO];  
  58.     [buffer setLength:0];  
  59. }  
  60.   
  61. //收到响应  
  62. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{  
  63.     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;  
  64.     if(httpResponse && [httpResponse respondsToSelector:@selector(allHeaderFields)]){  
  65.         NSDictionary *httpResponseHeaderFields = [httpResponse allHeaderFields];  
  66.         totalLength = [[httpResponseHeaderFields objectForKey:@"Content-Length"] longLongValue];  
  67.         NSLog(@"totalLength is %lld",totalLength);  
  68.     }  
  69. }  
  70.   
  71. //接收数据  
  72. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{  
  73.     //NSLog(@"didReceiveData...");  
  74.     [buffer appendData:data];  
  75.       
  76.     double progressValue = totalLength==0?0:((double)([buffer length])/(double)totalLength);  
  77.     //更新进度条值  
  78.     [downloadImageDelegate updateDownProgress:progressValue];  
  79. }  
  80.   
  81. //下载完毕  
  82. -(void)connectionDidFinishLoading:(NSURLConnection *)connection{  
  83.     done = YES;  
  84.     UIImage *img = [[UIImage alloc] initWithData:buffer];  
  85.     [downloadImageDelegate imageDownLoadFinished:img];  
  86. }  
  87.   
  88. -(BOOL)isConcurrent {  
  89.     //返回yes表示支持异步调用,否则为支持同步调用  
  90.     return YES;  
  91.       
  92. }  
  93.   
  94. - (BOOL)isExecuting{  
  95.     return connection == nil;   
  96. }  
  97.   
  98. - (BOOL)isFinished{  

抱歉!评论已关闭.