2

I want to download a file with pause/resume functionality. I read apple documents, there I got NSUrldownload which supports the same but it is not available for iOS. I was trying with NSUrlconnection, but not working. I don't want to use any third party libraries, I want to implement it by myself, below is the code snippet which I tried.

NSString *fileName = [NSString stringWithFormat:@"~%@",[[url componentsSeparatedByString:@"/"] lastObject]];

int dataLength = [[self checkDocDirectoryforFileName:fileName] length];
//dataLength = 0;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

[request setValue:@"audio/mpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"bytes" forHTTPHeaderField:@"Accept-Ranges"];
[request setValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
[request setValue:[NSString stringWithFormat:@"%d",dataLength] forHTTPHeaderField:@"Content-Length"];
NSLog(@"Request header  %@", [request allHTTPHeaderFields]);
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
Exploring
  • 925
  • 6
  • 18
  • If you want to implement it by yourself check the source code of AFDownloadRequestOperation, it's open source. – 3lvis Feb 28 '14 at 06:59

2 Answers2

1

iOS 7.0 and above

NSURLSession especially NSURLSessionDownloadTask provides this functionality.

The NSURLSession API provides status and progress properties, in addition to delivering this information to delegates. It supports canceling, restarting or resuming, and suspending tasks, and it provides the ability to resume suspended, canceled, or failed downloads where they left off.

Take a look to the docs.

iOS 5.0 and above

I would use AFDownloadRequestOperation for this. Take a look at this thread.

AFDownloadRequestOperation has additional support to resume a partial download, uses a temporary directory and has a special block that helps with calculating the correct download progress.

Community
  • 1
  • 1
3lvis
  • 4,190
  • 1
  • 30
  • 35
  • Thanks. But `NSURLSession` and `NSURLSessionDownloadTask` both are available for iOS 7.0 and later. Is it possible for below iOS 7.0? – Exploring Feb 28 '14 at 06:49
1

Please check it out this:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLDownload.html#//apple_ref/doc/uid/20001839-SW2

Hope, May it will help you,

:)

Gaurav
  • 299
  • 4
  • 15