我在NSOperation中使用此方法进行检查并创建一个文件夹:
- (void) checkAndCreateFolderWithPath:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathDaControllare = [[self getLibraryPath] stringByAppendingPathComponent:path];
NSError *error = nil;
BOOL isDir;
BOOL exists = [fileManager fileExistsAtPath:pathDaControllare isDirectory:&isDir];
if (exists) {
if (isDir) {
}
}
else {
[fileManager createDirectoryAtPath:pathDaControllare
withIntermediateDirectories:YES
attributes:nil
error:&error];
NSLog(@"%@",error);
}
}
使用NSOperation我收到此错误: 错误域= NSCocoaErrorDomain代码= 512"操作无法完成。
如果我没有使用NSOperation,那么所有工作都是完美的,这就是nsoperation
- (void) main {
NSString *filePath = [fileDict objectForKey:@"url"];
NSString *urlStr = [NSString stringWithFormat:@"http://www.allmyapp.net/wp-content/iFormulario_Update/%@",filePath];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data) {
NSString *folderPath = [filePath stringByReplacingOccurrencesOfString:[filePath lastPathComponent] withString:@""];
[self checkAndCreateFolderWithPath:folderPath];
NSString *pathFile = [[self getLibraryPath] stringByAppendingString:filePath];
[data writeToFile:pathFile atomically:YES];
[self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:pathFile]];
[[NSNotificationCenter defaultCenter] postNotificationName:@"endFile" object:nil];
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
isExecuting = NO;
isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
}];
}
这是创建队列的方法:
for (NSDictionary *dict in fileDaScaricare) {
DownloadOperation *downloadOperation = [[DownloadOperation alloc] initWithDictionary:dict];
[self.operationQueue addOperation:downloadOperation];
}
答案 0 :(得分:3)
您可以尝试这样的事情:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"/MyFolder"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *docFolderPath = [stringPath stringByAppendingString:[NSString stringWithFormat: @"/%@", self.downloadedFilename]];
[data writeToFile:docFolderPath atomically:YES];
它对我有用,我可以在MyFolder中下载文件。希望对你有效。如果有效,请告诉我。