Search code examples
iosobjective-csqlitensdatansfilemanager

convert sqlite database to nsdata and back


I converted sqlite file to NSData to save it in document directory. Now I'm converting it to sqlite file and saving that file in document directory, but the new sqlite file is not a valid sqlite file and code doesn't read data from it now. Below is the code I'm using to convert NSData to sqlite file:

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


What is wrong in my code, I think all time i am creating new sqlite file but how to solve this problem?
Can anybody help me how I can convert NSData to sqlite file. Should I write sqlite file in library and then access it from there ? But every update would decrypt sqlite file, i have to decrypt it.


Solution

  • If the file exists already, your code will decrypt and overwrite it. If it doesn't, you write an encrypted copy of a default database to the disk. So by default you have an encrypted file which will not be usable.