0

I am downloading a file with AFNetworking using an AFHTTPRequestOperation.

I want the user to be able to resume the download after it fails (from either a time out, or a lost connection...).

How would I do this?

I have read that AFDownloadRequestOperation does this, but this is not officially part of AFNetworking, and it is not up to date.

How do I resume a failed download?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
NickProvost
  • 367
  • 5
  • 22
  • GO throght this link may be it will help you.http://stackoverflow.com/questions/12173744/afnetworking-pause-resume-downloading-big-files –  Sep 24 '15 at 03:17
  • @Bhumika This technique uses AFDownloadRequestOperation. I have already seen this link. But AFDownloadRequestOperation is not being updated so I don't want to use it and then it not working later on. Also was not able to make it work to resume a fail. – NickProvost Sep 24 '15 at 14:03

1 Answers1

1

So I was able to resume by doing this:

First I make my app remember the "totalBytesRead" and "totalBytesExpectedToRead".

 [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {...}

Then, when the download fails, I have a retry button. When the user clicks the button, I call this code

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:@"www.myfileURL.com/file.mp4" cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

NSString* range = [NSString stringWithFormat:@"bytes=%lli-%lli", totalBytesRead, totalBytesExpectedToRead];
[request setValue:range forHTTPHeaderField:@"Range"];


operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:myPath append:YES];
  1. Make sure you properly set the http header for range in the format "bytes=fromBytes-totalBytes". An example would be "bytes=3200-12000"

  2. Make sure that when you make the new operation, you change the output stream to APPEND:YES. This is so your downloaded bytes append to the previously downloaded ones.

NickProvost
  • 367
  • 5
  • 22