Reputation: 935
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];
Upvotes: 2
Views: 999
Reputation: 4180
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.
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.
Upvotes: 1