I need to implement a subclass of NSOperation
which does a file upload to a HTTP server and with an option that the user can cancel the file upload during operation.
Here is the code at the moment:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:20];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"------WebKitFormBoundary4QuqLuM1cE5lMwCy";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSString *FileParamConstant = @"uploadFile";
NSData *imageData = [[NSData alloc] initWithContentsOfFile:imagePath];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:11];
[parameters setValue:@"Value" forKey:@"Server_required_param"];
NSString *urlString = @"http://www.omeuendereco/uploadFile.php";
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", FileParamConstant, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setURL:[NSURL URLWithString:urlString]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:up
startImmediately:YES];
[connection start];
the problem is that i have to implement a NSOperationqueue in this code and i dont know how. Then with the subclass of NSOperation i will be able to cancel the upload operation.