I know this question was asked many times on SO, but I didn't manage to make it work in my project...
So, I want to subclass NSOperation
and make it download a file using NSURLConnection
. What is the right way to do it?
here is my code which doesn't work:
First, I'm adding all my operations in a loop:
DownloadFileOperation *operation;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
for (int i=0; i<10; i++) {
operation = [[DownloadFileOperation alloc] init];
operation.urlString = pdfUrlString;
[queue addOperation:operation];
operation = nil; }
And here is my subclass:
@interface DownloadHandbookOperation : NSOperation <NSURLConnectionDelegate>
{
}
@property (strong, nonatomic) NSString *urlString;
@end
@implementation DownloadHandbookOperation
{
NSString *filePath;
NSFileHandle *file;
NSURLConnection * connection;
}
- (void)start
{
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}
NSURL *url = [[NSURL alloc] initWithString:[self.urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:@"Basic ***=" forHTTPHeaderField:@"Authorization"];
connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
{
NSString *filename = [[conn.originalRequest.URL absoluteString] lastPathComponent];
filename = [filename stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:filename];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
file = [NSFileHandle fileHandleForUpdatingAtPath:filePath] ;
if (file)
{
[file seekToEndOfFile];
}
else
[self finish];
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
if (file) {
[file seekToEndOfFile];
}
[file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
[file closeFile];
[self finish];
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
connection = nil;
[self finish];
}
- (void)cancel
{
[super cancel];
[connection cancel];
}
- (void)finish
{
NSLog(@"operationfinished.");
}
@end
What am I doing wrong?