我将 sqlite
文件转换为 NSData
以将其保存在文档目录中。现在我将它转换为 sqlite
文件并将该文件保存在文档目录中,但是新的 sqlite
文件不是有效的 sqlite 文件,代码不会从中读取数据现在。下面是我用来将 NSData
转换为 sqlite 文件的代码:
-(void)openDataBase{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Demo.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
{
NSData *data=[[NSData alloc]initWithContentsOfFile:writableDBPath];
NSString * _key = @"111";
NSData *decryptedData = [data AES256DecryptWithKey:_key];
[fileManager createFileAtPath:writableDBPath contents:decryptedData attributes:nil];
return;
}
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Demo.sqlite"];
NSData *SqliteData = [NSData dataWithContentsOfFile:defaultDBPath];
NSString * _key = @"111";
NSData *encryptedData = [SqliteData AES256EncryptWithKey:_key];
success= [fileManager createFileAtPath:writableDBPath contents:encryptedData attributes:nil];
if (!success)
{
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);} }
我的代码有什么问题,我想我一直在创建新的 sqlite 文件,但如何解决这个问题?
谁能帮助我如何将 NSData
转换为 sqlite 文件。
我应该在库中编写 sqlite 文件然后从那里访问它吗?
但是每次更新都会解密sqlite文件,我必须解密它。
最佳答案
如果文件已经存在,您的代码将解密并覆盖它。如果没有,您将默认数据库的加密副本写入磁盘。因此,默认情况下,您有一个无法使用的加密文件。
关于ios - 将 sqlite 数据库转换为 nsdata 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20016997/