xcode sqlite3 remove database error - xcode

I am using sqlite3 for my iOS project.
When login/logout i want to recreate the whole db.
(i can do "delete from table;" but there are ~10 tables and when i need a table more i have to be careful about writing the delete code too)
So i searched for deleting the db; but i found that it can not be done with query.
It is said that i have to remove it from filesystem;
my code is;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *dbPathDB=[appDelegate getDBPath];//dbname.sqlite
//to remove the db
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"dbname.sqlite"];
//both of them works same if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
if(filePath){
NSLog(#"it is removed now");
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
//recreating the db
if (sqlite3_open([dbPathDB UTF8String], &database) == SQLITE_OK) {
NSLog(#"db is created");
}
When i try it on device, when i first login (no removing database yet) everything is ok, when i logout and login again, i got errors about inserting the data (but it can connect to db, that part works, error is about inserting the same row again).
And i stop the device and run it again and login i got no insert errors because the db is clean..
It looks like db file is removed but db is on cache or sth like that? How can i remove and create the same db and then insert the data without errors?

This one works:
-(void)removeDB {
// Check if the SQL database has already been saved to the users phone
// if not then copy it over
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
success = [fileManager fileExistsAtPath:[appDelegate getDBPath]];
if(success) {
[fileManager removeItemAtPath:[appDelegate getDBPath] error:&error];
NSLog(#"This one is the error %#",error);
return;
}
//recreating the db
if (sqlite3_open([[appDelegate getDBPath] UTF8String], &database) == SQLITE_OK) {
NSLog(#"db is created");
}
}

Related

How to use hardcoded file path names with sandbox

Ok, yes I know now that you can not use hardcoded paths with sandbox. Up to this point I have not delt with sandbox, so I never encountered it.
I have a Coredata App (Mac OSx) and I used the default save code and the default path location (user/...../applicationsupport/... This, of coarse, is not acceptable in the sandbox.
Without requiring the user to manually open the data file each time the program is launched, is there another way to deal with this?
I would appreciate any input/suggestions.
Thanks You
Sandbox doesn't mean there isn't any access to files and folders without user selection. As it said in App Sandbox in Depth article there's container directory you still having access to.
For taking a path to your Application Support-directory you should use the same code whenever you use Sandboxing or not.
+ (NSString *)executableName
{
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleExecutable"];
if(!executableName || executableName.length==0)
return nil;
return executableName;
}
- (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory
inDomain:(NSSearchPathDomainMask)domainMask
appendPathComponent:(NSString *)appendComponent
error:(NSError **)errorOut
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory,domainMask,YES);
if ([paths count]==0)
return nil;
NSString *resolvedPath = [paths objectAtIndex:0];
if (appendComponent)
resolvedPath = [resolvedPath stringByAppendingPathComponent:appendComponent];
NSError *error;
BOOL success = [self createDirectoryAtPath:resolvedPath withIntermediateDirectories:YES attributes:nil error:&error];
if (!success)
{
if (errorOut)
*errorOut = error;
return nil;
}
return resolvedPath;
}
- (NSString *)applicationSupportDirectory
{
NSError *error;
NSString *result = [self findOrCreateDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask
appendPathComponent:[self executableName] error:&error];
if (error)
return nil;
return result;
}

How to make an OSX app use a sqlite database in the bundle?

I have an app that is intended to ship with a pre-populated sqlite database. I will include that database on the bundle. How do I modify the delegate to use that database instead of generating a new one?
This is my first serious app on OSX.
The current methods on the delegate is like this right now:
// Returns the directory the application uses to store the Core Data store file. This code uses a directory named "com.addfone.LoteriaMac" in the user's Application Support directory.
- (NSURL *)applicationFilesDirectory
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *appSupportURL = [[fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] lastObject];
return [appSupportURL URLByAppendingPathComponent:#"com.myApp.BotMax"];
}
// Creates if necessary and returns the managed object model for the application.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"BotMax" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.)
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator) {
return _persistentStoreCoordinator;
}
NSManagedObjectModel *mom = [self managedObjectModel];
if (!mom) {
NSLog(#"%#:%# No model to generate a store from", [self class], NSStringFromSelector(_cmd));
return nil;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *applicationFilesDirectory = [self applicationFilesDirectory];
NSError *error = nil;
NSDictionary *properties = [applicationFilesDirectory resourceValuesForKeys:#[NSURLIsDirectoryKey] error:&error];
if (!properties) {
BOOL ok = NO;
if ([error code] == NSFileReadNoSuchFileError) {
ok = [fileManager createDirectoryAtPath:[applicationFilesDirectory path] withIntermediateDirectories:YES attributes:nil error:&error];
}
if (!ok) {
[[NSApplication sharedApplication] presentError:error];
return nil;
}
} else {
if (![properties[NSURLIsDirectoryKey] boolValue]) {
// Customize and localize this error.
NSString *failureDescription = [NSString stringWithFormat:#"Expected a folder to store application data, found a file (%#).", [applicationFilesDirectory path]];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:failureDescription forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:#"YOUR_ERROR_DOMAIN" code:101 userInfo:dict];
[[NSApplication sharedApplication] presentError:error];
return nil;
}
}
NSURL *url = [applicationFilesDirectory URLByAppendingPathComponent:#"BotMax.storedata"];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
if (![coordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error]) {
[[NSApplication sharedApplication] presentError:error];
return nil;
}
_persistentStoreCoordinator = coordinator;
return _persistentStoreCoordinator;
}
The database file is named like BotMax.sqlite
thanks.
The simplest way to ship a pre-filled SQLite DB would be to copy the .sqlite file into the Application Support folder before the persistentStoreCoordinator is initialised.
The below code just copies the bundled DB. There are some things to consider before using that approach:
This simple approach only copies the initial DB once.
It does not consider merging or migrating existing stores (e.g when you ship an update with a changed model)
Core Data is using a new journal_mode since iOS 7 & OS X 10.9. This mode creates an additional file when saving the DB. (*.sqlite-wal). If the program that creates your pre-filled SQLite file was linked against OS X 10.9/iOS 7 or later SDKs, you'll also have to ship the .sqlite-wal file.
Alternatively, you can disable the WAL journal mode in the app that creates your pre-filled DB by passing #{ NSSQLitePragmasOption : #{ #"journal_mode" : #"DELETE" } }; as option dict to addPersistentStoreWithType
The following code is based on the standard Xcode template for non-document based Core Data apps:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator) {
return _persistentStoreCoordinator;
}
NSString* dbFilename = #"BotMax.sqlite";
NSURL* initialDBURL = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent:dbFilename];
NSURL* workingDBURL = [[self applicationFilesDirectory] URLByAppendingPathComponent:dbFilename];
NSFileManager* fileManager = [NSFileManager defaultManager];
NSURL* applicationFilesDirectory = [self applicationFilesDirectory];
NSError* error = nil;
if(![fileManager fileExistsAtPath:[workingDBURL path]])
{
BOOL result = [fileManager copyItemAtURL:initialDBURL toURL:workingDBURL error:&error];
if(!result)
{
[[NSApplication sharedApplication] presentError:error];
return nil;
}
}
...
}
objc.io issue #4 has a section about shipping pre-filled Core Data stores: http://www.objc.io/issue-4/importing-large-data-sets-into-core-data.html

How to specify working directory for sqlite3_open

Working in xCode everything works OK if I execute by double-clicking the project down in the working directory but not from xCode itself doing a Build and Run. Then the database isn't being found correctly.
How do I modify...
sqlite3_open("Airports.sqlite", &db);
so it can find Airports.sqlite in the current working directory?
Copy your database to your applications directory and after that you can use your database :)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *dbPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Airports.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!succes){
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Airports.sqlite"];
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
else
NSLog(#"Succesfully created writable database");
}

xcode EGODatabase update

I am trying to do a simple update to a sqlite database using EGODatabase and although the code runs the update does not occur?
NSArray *params = [NSArray arrayWithObjects:#"TEST", nil];
EGODatabase *database = [EGODatabase databaseWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"db_USBV1.sqlite3"]];
[database executeQuery:#"update users set locked = 0 where UID = ?" parameters:params ];
I saw on previous post that must copy the db to the users directory which i am doing as below;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:#"db_USBV1.sqlite3"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:filePath]) {
NSError *error = nil;
[fileManager copyItemAtPath:[[NSBundle mainBundle] pathForResource:#"db_USBV1" ofType:#"sqlite3"] toPath:filePath error:&error];
}
[fileManager release];
But update is not occurring.
Any help much appreciated.
Thanks,
Mike
Thanks for the pointers. I was still attempting to work with the file in the bundle and not the file that was copied.

How to redirect the nslog output to file instead of console

I have cocoa application running on OS X. I have used NSLog for debugging purpose. Now I want to redirect the log statements to file instead of console.
I have used this method but it results logging in Console as well as in file.
- (BOOL)redirectNSLog
{
// Create log file
[#"" writeToFile:#"/NSLog.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
id fileHandle = [NSFileHandle fileHandleForWritingAtPath:#"/NSLog.txt"];
if (!fileHandle) return NSLog(#"Opening log failed"), NO;
[fileHandle retain];
// Redirect stderr
int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
if (!err) return NSLog(#"Couldn't redirect stderr"), NO;
return YES;
}
Is it possible to not have log statement in console but only in file ??
Step 1: Include following function in AppDelegate:
- (void) redirectConsoleLogToDocumentFolder
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *logPath = [documentsDirectory stringByAppendingPathComponent:#"console.log"];
freopen([logPath fileSystemRepresentation],"a+",stderr);
}
Step 2: Call this function at the start of function applicationDidFinishLaunchingWithOptions...
Thats it, Every NSLog() will now get redirected to this console.log file, which you can find in the documents directory.
Recently i have faced similar requirement and this is how i have done it.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[self redirectConsoleLogToDocumentFolder];
return YES;
}
- (void) redirectConsoleLogToDocumentFolder
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *logPath = [documentsDirectory stringByAppendingPathComponent:#"console.txt"];
freopen([logPath fileSystemRepresentation],"a+",stderr);
}
And Now if you want to this console to user
-(void)displayLog{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *logPath = [documentsDirectory stringByAppendingPathComponent:#"console.txt"];
NSError *err = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:logPath
encoding:NSUTF8StringEncoding
error:&err];
if (fileContents == nil) {
NSLog(#"Error reading %#: %#", logPath, err);
} else {
self.textView.text = fileContents;
}
}
You may be interested in CocoaLumberjack. It is a very flexible logging framework for both Mac OS X and iOS. One logging statement can be sent not only to the console but to a file simultaneously. Plus it is actually faster then NSLog. I use it in a project that has common code for both OS X and iOS.
NSLog is made to log into the console. You need to define your own function MyLog or whatever, and replace all occurrences of NSLog into MyLog.

Resources