The use of nsoperation (download-related) images and files are both resumable images gradually displayed.

Source: Internet
Author: User









//// 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 _ canceled;}-(ID) initwithurlstring :( nsstring *) URL; @ property (readonly) nsdata * data; @ property (nonatomic, assign) ID <imagedownloaderdelegate> delegate; @ property (nonatomic, strong) nsobject * delpara; @ property (nonatomic, strong) implements * cancelledlock; @ end @ protocol imagedownloaderdelegate @ optional // The image download is completed.-(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]; // process events asynchronously, and set proxy _ connection = [nsurlconnection connectionwithrequest: _ Request delegate: Self]; while (_ connection! = Nil) {[[nsunloop currentrunloop] runmode: nsdefaultrunloopmode beforedate: [nsdate distantfuture] ;}}# Pragma mark nsurlconnection delegate method // receives data (incremental) -(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"]; _ canceled = yes; [self didchangevalueforkey: @ "iscancelled"]; [[self cancelledlock] unlock];}-(bool) iscancelled {bool result; [[self cancelledlock] Lock]; Result = _ canceled; [[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];    }];


Resumable download

NSMutableURLRequest *fileRequest = [NSMutableURLRequest requestWithURL:self.downloadURL                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy                                                           timeoutInterval:kFileDefaultTimeout];
If the file exists, resumable upload

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

Then start the download
  _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"];    }



The use of nsoperation (download-related) images and files are both resumable images gradually displayed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.