ios如何将sqlite文件导入app的文档目录?

How to import sqlite file into app's document directory in ios?

当我下载该数据库文件时,我想通过电子邮件和其他设备从我的应用程序导出我的整个数据库,它可以直接在应用程序中打开并用该数据库文件替换我现有的数据库文件。

我已经通过邮件导出了我的数据库文件 (.sqlite),我想将该文件从邮件导入到我的应用程序中。我还实现了邮件文件可以直接在我的应用程序中打开的功能。但我想直接从邮件中导入该数据库文件。那我该怎么做呢?

或者我可以用我的应用程序数据库替换那个文件吗?

这个 link 有助于解决您在 SQLITE 中的所有问题,

点赞将Sqlite文件复制到Docs目录,

还有 Select 查询、插入、删除、更新各种类型的记录等等...等等...

检查 + (NSString*) copyDBFile 方法link 满足你的要求

SQLite Programing : Initial Steps - By iOSCodeGUIDE

//Commen method for DAtaBase Copy
+ (NSString*) copyDBFile
{
    NSString *docsDirectoryPath;
    NSArray *dirPaths;
    NSString *databasePath;
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDirectoryPath = [dirPaths objectAtIndex:0];
    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDirectoryPath stringByAppendingPathComponent: @"SqliteTable.db"]];

    BOOL isSuccess = [fileManager fileExistsAtPath: databasePath ];

    if (!isSuccess)
    {
        NSError *error;
        NSString *defaultDBPath=[[NSBundle mainBundle]pathForResource:@"SqliteTable" ofType:@"db"];
        // NSLog(@"path :%@", defaultDBPath);
        isSuccess = [fileManager copyItemAtPath:defaultDBPath toPath:databasePath error:&error];

        if (! isSuccess)
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }

    NSLog(@"%@",databasePath);

    return databasePath;

}

无法完全理解您的问题,但这里有一段代码可以提供任何线索,说明如何替换文档目录中的现有文件:

    //Reference the path to the documents directory.
    NSString *documentDir =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //Get the path of old file.
    NSString *filePath = [documentDir stringByAppendingPathComponent:@"File.sqlite"];

   if([[NSFileManager defaultManager] fileExistsAtPath: filePath])
   {
      [fileManager removeItemAtPath:filePath error:&error] //Delete old file
   }
   //Copy New File.sqlite from Resource Bundle.
   NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"sqlite"];
   [fileManager copyItemAtPath:resourcePath toPath:filePath error:&error]; 

我想你正在寻找以下方法,

- (BOOL)replaceItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL backupItemName:(nullable NSString *)backupItemName options:(NSFileManagerItemReplacementOptions)options resultingItemURL:(NSURL * _Nullable * _Nullable)resultingURL error:(NSError **)error NS_AVAILABLE(10_6, 4_0);

您可以使用 NSFileManager 的实例或对象调用此方法。您可以将源路径和目标路径作为 fileUrl ([NSURL fileURLWithPath:@"path string"];) 传递,它将替换目标路径中的数据!

您应该使用 iOS 共享扩展来首先从邮件应用程序导入数据库文件。这里有一个tutorial,大家可以参考一下。

// Returns 应用程序的持久存储协调器。 // 如果协调器尚不存在,则创建它并将应用程序的商店添加到它。

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil)
{
    return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"yourSqlite.sqlite"];

NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"yourSqlite.sqlite" ofType:nil];

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;

if  (![[NSFileManager defaultManager] fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:@"yourSqlite.sqlite"] ]) {

    if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:[documentsDirectory stringByAppendingPathComponent:@"yourSqlite.sqlite"] error:&error]){
        NSLog(@"Default file successfully copied over.");
    } else {
        NSLog(@"Error description-%@ \n", [error localizedDescription]);
        NSLog(@"Error reason-%@", [error localizedFailureReason]);
    }
}

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _persistentStoreCoordinator;
}