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

Can't copy Folder's contents from app bundle to document directory

这里我引用了此 link 将文件夹从应用程序包复制到文档 directory.Folders 已成功创建但不是 contents.I 将此代码写入我的 "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;
}

如果您想复制 directory/folder 及其所有内容,则需要递归复制方法。在这里您可以无限循环遍历目录的内容和子内容,直到所有内容都被复制。因此:

- (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...
    });
});

我得到了答案..!,问题是我想将一个文件夹从应用程序包复制到我的应用程序文档 directory.so,首先手动创建名为 temp 的文件夹,然后将我的内容放入temp 我想要在我的应用程序中使用的文件夹,而不是我将 temp 文件夹重命名为 temp.bundle 这将要求用户确认。就给确定。比我在 AppDelegate.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 )
    {
        NSLog(@"IN");
        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"temp" ofType:@"bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
        NSString *path = [bundle resourcePath];
        //NSLog(@"\nPath:-\n%@",path);
        NSFileManager *fm = [NSFileManager defaultManager];
        NSError *error = [[NSError alloc] init];
        NSArray *directoryAndFileNames = [fm contentsOfDirectoryAtPath:path error:&error];
        //NSLog(@"\ndirectoryAndFileName:-\n%@",directoryAndFileNames);
        NSString* from=[NSString new];
        from=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[directoryAndFileNames firstObject]]];
        success1=[[NSFileManager defaultManager] copyItemAtPath:from toPath:writableDBPath1 error:&error1];
        if(success1){
            NSLog(@"Done");
        }
        else{
            NSLog(@"NOT Done");
        }
    }
}

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