无法将文件夹的内容从应用程序包复制到文档目录

时间:2015-02-24 11:18:19

标签: objective-c ios8 nsfilemanager

这里我引用了这个link来将应用程序包中的文件夹复制到文档目录。文件夹创建成功但不是它的内容。我将此代码写入我的"AppDeleget.m"。我想复制带有子目录的主文件夹。

- (void) copyFolder {
    BOOL success1;
    NSFileManager *fileManager1 = [NSFileManager defaultManager];
    fileManager1.delegate = self;
    NSError *error1;
    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
    NSString *writableDBPath1 = [documentsDirectory1 stringByAppendingPathComponent:mainFolder];
    success1 = [fileManager1 fileExistsAtPath:writableDBPath1];
    if (success1 )
    {
        NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:mainFolder];
        NSLog(@"\ndefault path %@",defaultDBPath1);
        success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
        NSLog(@"\n#Error:-\n%@",error1.localizedDescription);
    }
    else {
        if (![[NSFileManager defaultManager] fileExistsAtPath:writableDBPath1])
            [[NSFileManager defaultManager] createDirectoryAtPath:writableDBPath1 withIntermediateDirectories:NO attributes:nil error:&error1];
    }
    NSLog(@"\nWritableDB path %@",writableDBPath1);
}

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
    if ([error code] == 516) //error code for: The operation couldn’t be completed. File exists
        return YES;
    else
        return NO;
}

2 个答案:

答案 0 :(得分:1)

如果要复制目录/文件夹及其所有内容,则需要递归复制方法。在这里,您可以无限循环浏览目录的内容和子内容,直到所有内容都被复制。正是如此:

- (BOOL)recursiveCopyFilesAtPath:(NSString *)origin toPath:(NSString *)destination
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:origin]) {
        if (![[NSFileManager defaultManager] fileExistsAtPath:destination]) {
            NSError *error1 = nil;
            if (![[NSFileManager defaultManager] createDirectoryAtPath:destination withIntermediateDirectories:YES attributes:nil error:&error1]) {
                NSLog(@"Failed to create directory at path: %@. Error: %@.", destination, error1.localizedDescription);
                return NO;
            }
        }
        // Recursive copy
        [self copyContentsOfDirectory:origin toPath:destination];
    }
    else {
        NSLog(@"No files at path: %@", origin);
        return NO;
    }
    return YES;
}

- (void)copyContentsOfDirectory:(NSString *)dir toPath:(NSString *)path
{
    for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:nil]) {
        NSURL *url = [NSURL fileURLWithPath:[dir stringByAppendingPathComponent:file]];
        NSNumber *isDirectory = nil;
        if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) {
            NSLog(@"Failed to get resource value for item at path: %@", [dir stringByAppendingPathComponent:file]);
        }
        else {
            if (isDirectory.boolValue) {
                // Create equivalent directory at new path...
                NSError *erro = nil;
                if (![[NSFileManager defaultManager] createDirectoryAtPath:[path stringByAppendingPathComponent:file] withIntermediateDirectories:NO attributes:nil error:&erro]) {
                    NSLog(@"Failed to create directory at path: %@. Error: %@", [path stringByAppendingPathComponent:file], erro.localizedDescription);
                }
                // This is where the process loops until there are no subdirectories left...
                [self copyContentsOfDirectory:[dir stringByAppendingPathComponent:file] toPath:[path stringByAppendingPathComponent:file]];
            }
            else {
                NSError *err = nil;
                if (![self copyFileFromPath:[dir stringByAppendingPathComponent:file] toPath:path error:err]) {
                    NSLog(@"Failed to copy item at path: %@. Error: %@", [dir stringByAppendingPathComponent:path], err.localizedDescription);
                }
            }
        }
    }
}

- (BOOL)copyFileFromPath:(NSString *)path toPath:(NSString *)dest error:(NSError *)error
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return [[NSFileManager defaultManager] copyItemAtPath:path toPath:[dest stringByAppendingPathComponent:dest.lastPathComponent] error:&error];
    }
    return NO;
}

注意:这是我刚刚用来给你提供想法的未经测试的代码。

另请注意,这可能是一项冗长的任务,不应在主线程上执行,应该像这样调用...

// Prep UI
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
     if (![self recursiveCopyFilesAtPath:origin toPath:destination]) {
            NSLog(@"Failed to copy files at path: %@", origin);
     }
     dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI and notify user...
    });
});

答案 1 :(得分:0)

我得到了答案..!,问题是我要将应用程序包中的文件夹复制到我的应用程序的文档目录中。首先,手动创建名为temp的文件夹,而不是将我的内容放入{{1}我在我的应用程序中想要的文件夹比我将temp文件夹重命名为temp这将要求用户确认。好吧。我使用temp.bundle中的波纹管代码来使事情成为可能。

AppDelegate.m

此代码将运行一次,将包含内容的文件夹放到应用程序的文档目录中。

相关问题