如何将文件从主捆绑包复制到文档文件夹 [英] how to copy file from main bundle to Document Folder

查看:199
本文介绍了如何将文件从主捆绑包复制到文档文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查Document文件夹中的一个文件.我想如果该文件在Document文件夹中不存在,请将其从主捆绑包复制到Document文件夹.我写这段代码和要复制的文件,但是我的问题在这里..... !!!!我的文件是.sqlite文件(数据库文件),当复制到文档文件夹中时自身没有数据!!!为什么???而此文件位于主捆绑包中时,其自身就有数据.

I want to check one file in Document folder.I want if this file not exist in document folder copy it from main bundle to document folder. I write this code and this file to be copy but my problem here.....!!!! my file is .sqlite file (Database file) and when copy to document folder hasn't data in self!!!! why??? while the this file when is in main bundle has data in self.

这是我的代码,但我不知道为什么不起作用!!!

this is my code but I don't know why not work!!!!

#define DataName @"mydatabase.sqlite"


- (void)viewDidLoad
{
    [self CopyDatabase];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (NSString*)DatabasePath
{
    NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DocumentDir = [Paths objectAtIndex:0];
    //NSLog(@"%@",DocumentDir);
    return [DocumentDir stringByAppendingPathComponent:DataName];

}

- (void)CopyDatabase
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    success = [fileManager fileExistsAtPath:[self DatabasePath]];
    NSString *FileDB = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DataName];
    if (success)
    {
        NSLog(@"File Exist");
        return;
    }
    else
    {
        [fileManager copyItemAtPath:FileDB toPath:[self DatabasePath] error:nil];
    }

}

推荐答案

我不认为您的文档文件夹正在更新,因为该数据库存在较旧的版本.您可以使用以下方法清除文档目录,并将其添加到viewDidLoad的顶部:

I don't think your documents folder is updating because an older version of that db exists. You can purge your documents directory with the following method, and add it to the top of your viewDidLoad:

- (void)viewDidLoad
{
    [self purgeDocumentsDirectory];
    [self CopyDatabase];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)purgeDocumentsDirectory
{
    NSLog(@"Purging Documents Directory...");
    NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error = nil;
    for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
        [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
    }
}

这篇关于如何将文件从主捆绑包复制到文档文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆