我需要实现一个子类,NSOperation
该子类将文件上传到 HTTP 服务器,并且用户可以在操作期间取消文件上传。
这是目前的代码:
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];
问题是我必须在这段代码中实现一个 NSOperationqueue 我不知道如何。然后使用 NSOperation 的子类,我将能够取消上传操作。