add Separate .sqlite file to ios project - ios

I have created a myDB.sqlite database from SQLite Manager firefox addon. I want to add this myDB.sqlite file to my project. Then I can write functions to get data from tables.
I tried to add the myDB.sqlite file to project folder & create a filepath like this. But I think this filepath is wrong.
-(NSString *) filePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"document.sqlite"];
return path;
}
Does it correct to add myDB.sqlite file to the project folder? or where should I save this myDB.sqlite file & what is the filepath I should use?

add your myDB.sqlite file in your project. by right click your project name=> add files to ""projectName", then add it.
to get your file path you can add this in your appDelegate
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath
{
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
//NSLog(#"dbpath : %#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"myDB.sqlite"];
}
in your did finish with launching method call [self copyDatabaseIfNeeded];

I assume you have successfully copied sqlite db into project's folder. So you have sqlite Database in your app's bundle now.
So you need to copy database from app's bundle to document directory of device/simulator using following code. Write these in AppDelegate.m
- (void) copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
// First, test for existence.
if (![fileManager fileExistsAtPath:folderPath])
[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&error]; //Create folder
NSString *dbPath = [folderPath stringByAppendingPathComponent:#"document.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"document.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"document.sqlite : Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/** Database copy is not exist **/
[self copyDatabaseIfNeeded];
// Override point for customization after application launch.
return YES;
}

-(void)addSqlFileIfNotExists {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:#"document.sqlite"];
BOOL exits = [fileManager fileExistsAtPath:writableDBPath];
if(exits) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"document.sqlite"];
BOOL exit = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!exit)
NSLog(#"%#",[error localizedDescription]);
}

Related

Keep on changing the address of database in IOS

Everytime I run my app, database address is changed so my update or retrieval is not successfully working.
Any one can help me why this is happening with me... here my code to copy my database to the directory.
(BOOL)createDB
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
dataPath=dbPath;
databasePath = dbPath;
NSLog(#"Path is: %#",dbPath);
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"babynames.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
return success;
}
Here is getDBPathCode
- (NSString *)getDBPath
{`NSSearchPathForDirectoriesInDomains`
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
'NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
//NSLog(#"dbpath : %#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"babynames.sqlite"];'
}

Better way to save sqlite database file(.db) in ios application

What is better way to copy sqlite database file(.db) in ios application means that in NSBundle or in Document folder.
You can try this
- (void)createEditableCopyOfDatabaseIfNeeded
{
// 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:#"DB.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"KURANDB2.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}

calling sqlite database from the bundle

I am working with the sqlite database and everything is going well. I added 4 entries in the table, and then added textview on my xib file. Now i want that this data should be fetched from the sqlite database which is placed in the bundle of the project. But i am not getting how to call this database from the bundle to thedirectory path. Please help me out regarding this issue.
Use this code:
First call this method which will check wheter dbfile is stored in documents Directory or not. If not It will write your file to documents directory.
-(void)openDatabase {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"databasefilename.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath
error:&error];
if (!success)
NSLog(#"Failed to create writable database file with message '%#'.",
[error localizedDescription]);
}
}
- (NSString *) getDBPath {
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,
NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"databasefilename.sqlite"];
}
Then check in Appdelegate or any other class where you want:
if (sqlite3_open([[self getDBPath] UTF8String], &YOUR_SQLITE3_OBJECT) == SQLITE_OK) {
NSLog(#"database opened successfully");
}

Copy Folder from main bundle to documents directory in iphone

I am having an app in which I have a folder named "Images" in my main bundle.
In This folder there is another folder called "Images1" containing some images.
When my app Launch I want the folder "Images" on the documents directory.
I want to fetch images from the folder "Images1".
But I can't get my images in the folder "Images" at documents directory with the following code.
Edited
BOOL success1;
NSFileManager *fileManager1 = [NSFileManager defaultManager];
NSError *error1;
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *writableDBPath1 = [documentsDirectory1 stringByAppendingPathComponent:#"Images/Images1"];
success1 = [fileManager fileExistsAtPath:writableDBPath1];
if (success1) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Images/Images1"];
NSLog(#"Default : %#",defaultDBPath1);
success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
if (!success1) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error1 localizedDescription]);
}
Please help me.
Are you sure that you have the files in your folder tree?
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"/Images/Images1"];
usually when xcode make a package it flatten the directory contents. So first check you have all the things in your source folder. Even if you see that the folder is shown in your package explorer, when copied in the app, you will see the images are in the root folder. To avoid this, when you add the Image folder, in your xcode project, you can check the option to 'create folder reference'.
However, your write may fail because of an overwrite. In that case you have to implement a delegate method for NSFileManager given below.
- (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:#"/Images"];
success1 = [fileManager1 fileExistsAtPath:writableDBPath1];
if (success1 )
{
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Images"];
NSLog(#"default path %#",defaultDBPath1);
success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
} else {
if (![[NSFileManager defaultManager] fileExistsAtPath:writableDBPath1])
[[NSFileManager defaultManager] createDirectoryAtPath:writableDBPath1 withIntermediateDirectories:NO attributes:nil error:&error1];
}
}
- (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;
}

ios fmdb load db from file

I use sqlite and fmdb wrapper. My code for load db is this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"biscuit.sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
I add biscuit.sqlite to my project, but this code create new file instead open existing one. How can I load this file?
If you only want to read data from your database, try to use the code below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"biscuit" ofType:#"sqlite"];
If you need read/write access, you have to copy your database to a writable user folder first.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"biscuit.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"biscuit.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success) {
NSLog(#"Failed to create writable DB. Error '%#'.", [error localizedDescription]);
} else {
NSLog(#"DB copied.");
}
}else {
NSLog(#"DB exists, no need to copy.");
}

Resources