首页 > 代码库 > NSOperation 的使用(下载相关) 图片和文件都是可以的 断点续传 图片逐渐显示

NSOperation 的使用(下载相关) 图片和文件都是可以的 断点续传 图片逐渐显示









//
//  ImageDownloader.h
//  NSOperationTest
//
//  Created by ydc on 11-10-29.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol imageDownloaderDelegate;

@interface ImageDownloader : NSOperation 
{
    NSURLRequest* _request;
    
    NSURLConnection* _connection;
    
    NSMutableData* _data;
    
    BOOL _isFinished;
    
    BOOL _cancelled;
}

- (id)initWithURLString:(NSString *)url;

@property(readonly) NSData *data;
@property(nonatomic, assign) id<imageDownloaderDelegate> delegate;
@property(nonatomic, strong) NSObject *delPara;
@property(nonatomic, strong) NSRecursiveLock *cancelledLock;


@end

@protocol imageDownloaderDelegate

@optional

//图片下载完成的委托
- (void)imageDidFinished:(UIImage *)image para:(NSObject *)obj;

@end


//
//  ImageDownloader.m
//  NSOperationTest
//
//  Created by ydc on 11-10-29.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "ImageDownloader.h"


@implementation ImageDownloader



- (id)initWithURLString:(NSString *)url 
{
    
    self = [self init];
    if (self) {
        assert(url != nil);
        _request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
        _data = [NSMutableData data];
    }
    return self;
}

- (void)start {
    
    if (![self isCancelled]) {
        
        [NSThread sleepForTimeInterval:3];
        // 以异步方式处理事件,并设置代理
        
        _connection=[NSURLConnection connectionWithRequest:_request delegate:self];
        
        while(_connection != nil) {
            
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];   
            
        }
        
    }
    
}

#pragma mark NSURLConnection delegate Method

// 接收到数据(增量)时

- (void)connection:(NSURLConnection*)connection
    didReceiveData:(NSData*)data
{
    [_data appendData:data];
    if (self.delegate != nil){
        UIImage *img = [[UIImage alloc] initWithData:self.data] ;
        [_delegate imageDidFinished:img para:self.delPara];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
    if (self.delegate != nil)
    {
        UIImage *img = [[UIImage alloc] initWithData:self.data] ;
        [_delegate imageDidFinished:img para:self.delPara];
    }
    _connection=nil;
}

-(void)connection: (NSURLConnection *) connection didFailWithError: (NSError *) error
{
    _connection=nil;
}
- (void)cancelOnRequestThread
{
    [[self cancelledLock] lock];
    if ([self isCancelled]) {
		[[self cancelledLock] unlock];
		return;
	}
    [self willChangeValueForKey:@"isCancelled"];
    _cancelled = YES;
    [self didChangeValueForKey:@"isCancelled"];
    
    [[self cancelledLock] unlock];
}
- (BOOL)isCancelled
{
    BOOL result;
    
	[[self cancelledLock] lock];
    result = _cancelled;
    [[self cancelledLock] unlock];
    
    return result;
}
-(BOOL)isConcurrent
{
    return YES;
}
- (BOOL)isExecuting
{
    return _connection == nil; 
}
- (BOOL)isFinished
{
    return _connection == nil;  
}

@end

@property (strong, nonatomic)NSOperationQueue *queue;


 NSString *newUrl = [NSString stringWithFormat:@"http://static2.dmcdn.net/static/video/666/645/43546666:jpeg_preview_source.jpg?%d",(int)[NSDate timeIntervalSinceReferenceDate]];
    ImageDownloader *imageDownloader = [[ImageDownloader alloc]initWithURLString:newUrl];
    imageDownloader.delegate = self;
    [self.queue addOperation:imageDownloader];

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
        self.urlConnection = [NSURLConnection connectionWithRequest:request delegate:self];
    }];


下载文件断点续传

NSMutableURLRequest *fileRequest = [NSMutableURLRequest requestWithURL:self.downloadURL
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:kFileDefaultTimeout];
如果文件存在则 断点续传

_startFileSize = [[fm attributesOfItemAtPath:self.pathToFile error:nil] fileSize];
        NSString *range = [NSString stringWithFormat:@"bytes=%lld-", _startFileSize];
        [fileRequest setValue:range forHTTPHeaderField:@"Range"];

然后启动下载
  _connection = [[NSURLConnection alloc] initWithRequest:fileRequest
                                                  delegate:self
                                          startImmediately:NO];
    if (self.connection) {
        [self.connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                   forMode:NSDefaultRunLoopMode];
        [self willChangeValueForKey:@"isExecuting"];
        [self.connection start];
        [self didChangeValueForKey:@"isExecuting"];
    }