How do I download an image from a URL and save it to my computer? - objective-c

How would I download an image from a URL, and have that saved to the computer using Objective-C? This is what I got so far:
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *imageFromURL = [self getImageFromURL:#"https://www.google.com/images/srpr/logo11w.png"];
[self saveImage:imageFromURL withFileName:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
UIImage *imageFromWeb = [self loadImage:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
Xcode complains about UIIMage, trying to replace with NSImage. It also complains about an undeclared identifier 'self'.
I need to make an HTTP call to perform this as well. Explain this to me like I'm 5.

Here is the code to Save the image into document Directory.
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
if (imgName) {
//save Image From URL
[self getImageFromURLAndSaveItToLocalData:imgName fileURL:imgURL inDirectory:documentsDirectoryPath];
}
}
else{
// file exist
NSLog(#"file exist");
}
}
-(void) getImageFromURLAndSaveItToLocalData:(NSString *)imageName fileURL:(NSString *)fileURL inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
NSError *error = nil;
[data writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imageName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imageName);
}
}
And this is the one method code..
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
//save Image From URL
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]];
NSError *error = nil;
[data writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imgName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imgName);
}
}
else{
// file exist
NSLog(#"file exist");
}
}

This is my solution!
+(BOOL)downloadMedia :(NSString*)url_ :(NSString*)name{
NSString *stringURL = url_;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
return YES;
}
return NO;
}
+(UIImage*)loadMedia :(NSString*)name{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *img_ = [UIImage imageWithContentsOfFile:getImagePath];
return img_;
}

Related

mp4 video recorded from iPhone 8 not playing iPad mini 2 & website

I am capturing video using UIImagePickerController. Exporting video into mp4. Code is here:
- (NSString *)convertMOVToMp4:(NSURL *)url : (NSString *)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *dataPath = [documentsPath stringByAppendingPathComponent:#"/doctorphoto"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *videoPath1 = [dataPath stringByAppendingPathComponent:#"xyz2.mov"]; //Add the file name
NSString *movfilepath = videoPath1;
NSURL *videoURL = url;
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
[videoData writeToFile:videoPath1 atomically:NO];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movfilepath] options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
{
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetPassthrough];
videoPath1 = [self getLocalVideoPath:filename];
exportSession.outputURL = [NSURL fileURLWithPath:videoPath1];
NSLog(#"videopath of your mp4 file = %#",videoPath1); // PATH OF YOUR .mp4 FILE
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(#"Export failed: %#", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(#"Export canceled");
break;
default:
NSLog(#"Export success.");
[self.delegate onCompleteConvert: videoPath1 : anyobj];
break;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:movfilepath error:NULL];
}];
}
return videoPath1;
}
Its converting into mp4. Then uploading into AWS server. This link is streaming into iPhone 8, but not playing in iPhone 5S, iPad mini2. In website, audio is playing, but showing black screen.If I follow the same procedure from iPhone 5S or iPad mini, its working fine. Can anybody help me. Thanks in advance.
This change solved the problem:
- (NSString *)convertMOVToMp4:(NSURL *)url : (NSString *)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *dataPath = [documentsPath stringByAppendingPathComponent:#"/doctorphoto"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *videoPath1 = [dataPath stringByAppendingPathComponent:#"xyz2.mov"]; //Add the file name
NSString *movfilepath = videoPath1;
NSURL *videoURL = url;
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
[videoData writeToFile:videoPath1 atomically:NO];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movfilepath] options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
{
NSString *preset = AVAssetExportPreset1920x1080;
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:preset];
videoPath1 = [self getLocalVideoPath:filename];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// videoPath1 = [NSString stringWithFormat:#"%#/doctorphoto/%#", [paths objectAtIndex:0], filename];
exportSession.outputURL = [NSURL fileURLWithPath:videoPath1];
NSLog(#"videopath of your mp4 file = %#",videoPath1); // PATH OF YOUR .mp4 FILE
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse = true;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(#"Export failed: %#", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(#"Export canceled");
break;
default:
NSLog(#"Export success.");
[self.delegate onCompleteConvert: videoPath1 : anyobj];
break;
}
// UISaveVideoAtPathToSavedPhotosAlbum(videoPath1, self, nil, nil);
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:movfilepath error:NULL];
}];
}
return videoPath1;
}

How to save and load multiple photos into my local app in Objective C?

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
image=[info objectForKey:UIImagePickerControllerOriginalImage];
[self.images addObject:image];
[self.maintable reloadData];
[self dismissViewControllerAnimated:YES completion:NULL];
}
-(IBAction)savebutton:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,
NSUserDomainMask , YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImages"]];
for (int i=0; i<_images.count; i++) {
image=[_images objectAtIndex:i];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#"saved");
}
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);`
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImage.png"] ];
image = [UIImage imageWithContentsOfFile:path];
if(image != nil){
[self.images addObject:image];
}
return image;
}
You are on correct track,
On save button action, save images document directory's particular path and save image name in one array which you need to save in core data or preference whatever you preferred in your app
like this..
NSString *strImageName = #"image.png"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent: strImageName];
// Above you can give your custom path like #"App_Name/imageName" for unique identification
[pngData writeToFile:filePath atomically:YES];
[arrCoreData addObject: strImageName];
Once you have done(saved all your images then save image name in preference)
like this
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: arrCoreData];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"MyImageArray"];
When you want to fetch images and display it again,
You may follow this flow:
NSData *mainCatData = [[NSUserDefaults standardUserDefaults] objectForKey:#"MyImageArray"];
arrCoreData = [NSKeyedUnarchiver unarchiveObjectWithData:mainCatData];
Then using these images name you may fetch images back and display as you want..
To load image from document directory, You may use this function
- (UIImage*)loadImage:(NSString)strImageName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString: #"AppName/%#", strImageName] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
Hope it will help you :)
I did it and worked on my app:)
- (void)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (int i=0; i<fileArray.count; i++) {
NSString* path = [documentsDirectory stringByAppendingPathComponent:fileArray[i]];
image = [UIImage imageWithContentsOfFile:path];
[self.images addObject:image];
}
}
-(IBAction)savebutton:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask , YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
for (int i=0; i<_images.count; i++) {
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImages%d", i]];
image=[_images objectAtIndex:i];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#"saved");
}
}

UIImage gives nil

I'm quite new to iOS development. My app gets a file over a network, writes it as image.png and later on reads and displays the image. However, the display part is not working as my UIImage object is always set to nil (on the iOS simulator). I've tried implementing other answers from stackoverflow, but no luck.
Here's my code to save the file:
//inside utility class for model
NSFileHandle * handle = nil;
//For first packet of new file request
if(CountFileParts == 1)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"image.png"];
NSLog(#"%#",appFile);
handle = [NSFileHandle fileHandleForWritingAtPath:appFile];
if(handle == nil)
{
[[NSFileManager defaultManager] createFileAtPath:appFile contents:nil attributes:nil];
handle = [NSFileHandle fileHandleForWritingAtPath:appFile];
}
}
//For other incoming packets of the same request
else
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"image.png"];
//NSLog(#"%#",appFile);
handle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[handle seekToEndOfFile];
//NSLog(#"Writing continue in new file");
}
if(handle == nil)
NSLog(#"handle nil");
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
[handle writeData:data];
[handle closeFile];
if(index != -1 && index!= NSNotFound)
{
NSLog(#"Inside Bool");
self.isPlotReady = YES;//kvo in view-controller as shown below
self.isPlotReady = NO;
}
Here's my code to load the image file:
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:#"isPlotReady"])
{
self.isReady = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
[self updateUI];
}
}
-(void) updateUI
{
if(self.isReady)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self lsOwnDirectory:documentsDirectory];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"image.png"];
//NSLog(#"%#",appFile);
UIImage *img = [UIImage imageWithContentsOfFile:appFile];
if(img == nil)
NSLog(#"Couldn't find image");
else
{
UIImageView *imageView = [[UIImageView alloc] initWithImage:img] ;
[self.view addSubview:imageView];
}
}
}
//Prints Directory contents of input directory
- (void) lsOwnDirectory:(NSString *) currentpath {
NSError * error = [[NSError alloc] init];
NSFileManager *filemgr;
filemgr = [[NSFileManager alloc] init];
//currentpath = [filemgr currentDirectoryPath];
NSLog(#"Current Directory Path : %#",currentpath);
NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:currentpath error: &error];
for(NSString * file in files){
NSLog(#"%#", file);
}
}
It alway's prints "Couldn't find image" corresponding to the if statement, but I've seen the file is still there (lsOwnDirectory prints directory contents). Maybe I'm doing something basic wrong here. Thanks in advance.

UIImageJPEGRepresentation throws EXC BAD ACCESS

I have function, which received 2 arguments - image and number. Function below throws EXC BAD ACCESS on line "imgData = UIImageJPEGRepresentation(image, 1.0);". I don't know why :-( Any ideas?
- (void)saveImages:(UIImage*)image row:(int)row {
if (image != nil) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path1 = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%i.JPEG", row]];
NSString* path2 = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%is.JPEG", row]];
NSData* imgData;
imgData = UIImageJPEGRepresentation(image, 1.0);
[imgData writeToFile:path1 atomically:YES];
[self rotateIcon:image];
image = [self imageWithImage:image];
NSData* smalImgData = UIImageJPEGRepresentation(image, 1.0);
[smalImgData writeToFile:path2 atomically:YES];
}
}

SQLite Table does not exist

EDIT: SOLVED! answer below first code box
When i try to connect with a sqlite database (with a table TblTest). In debug mode in my app, the error is:
* Assertion failure in -[QueryClass getTestData:],
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cant build SQL to read item [no such table: TblTest]'
In release mode (simulator), it does not give an error but it will not read the database.
The code behaves like it can connect to the db, but can NOT read the TblTest?
I already reset the simulator and used clean and build.
Sorry for the long code:
#implementation QueryClass
#synthesize databaseName;
#synthesize databaseLite;
-(id)initWithDatabase:(NSString *)databaseNameP{
if(self = [super init]){
[self createEditableCopyOfDatabaseIfNeeded];
self.databaseName = databaseNameP;
self.databaseLite = [self getNewDBConnection];
}
return self;
}
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(#"Creating editable copy of database");
// 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:self.databaseName];
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:self.databaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message ‘%#’.", [error localizedDescription]);
}
}
- (sqlite3 *) getNewDBConnection{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:self.databaseName];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
-(NSMutableArray *)getTestData:(NSInteger) testId{
(NSMutableArray *testArray = [[NSMutableArray alloc]init];
int ret;
sqlite3_stmt *selStmt = nil;
const char *sql = "SELECT testId, name, FROM TblTest WHERE testId = ?";
if (!selStmt)
{ // build update statement
if (sqlite3_prepare_v2(self.databaseLite, sql, -1, &selStmt, NULL)!=SQLITE_OK)
{
selStmt = nil;
}
}
sqlite3_bind_int(selStmt, 1, testId);
if(!selStmt){
NSAssert1(0, #"Cant build SQL to read item [%s]", sqlite3_errmsg(self.databaseLite));
}
while ((ret=sqlite3_step(selStmt))==SQLITE_ROW)
{ // get the fields from the record set and assign to item
Test *test = [[Test alloc]init];
NSNumber *testId = [NSNumber numberWithInt: (int) sqlite3_column_int(selStmt, 0)];
NSString *name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(selStmt, 1)];
test.testId =testId;
test.name =name;
[testArray addObject:pill];
[test release];
}
sqlite3_reset(selStmt);
return [testArray autorelease];
}
//in my function i do:
qc = [[QueryClass alloc]initWithDatabase:#"databaseLite.sql"];
[qc getTestData:0];
I rewrote my code using this tutorial and it works like a charm. :)
Thanks
-(id)initWithDatabase:(NSString *)databaseNameP{
if(self = [super init]){
[self createEditableCopyOfDatabaseIfNeeded];
[self initializeDatabase];
}
return self;
}
// Creates a writable copy of the bundled default database in the application Documents directory.
- (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:#"databaseLite4.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:#"databaseLite4.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase {
// The database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.path = [documentsDirectory stringByAppendingPathComponent:#"databaseLite4.sqlite"];
}
When you solve your own problems, you should provide your solution as an answer rather than updating your question. It is possible (and recommended in this situation) to answer your own question and accept it as your answer. You will not gain any reputation for accepting your own answer, but the question will be correctly listed as solved.
Below is the answer I extracted from your question. Feel free to accept it.
I rewrote my code using this tutorial and it works like a charm. :)
Here's my solution:
-(id)initWithDatabase:(NSString *)databaseNameP{
if(self = [super init]){
[self createEditableCopyOfDatabaseIfNeeded];
[self initializeDatabase];
}
return self;
}
// Creates a writable copy of the bundled default database in the application Documents directory.
- (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:#"databaseLite4.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:#"databaseLite4.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase {
// The database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.path = [documentsDirectory stringByAppendingPathComponent:#"databaseLite4.sqlite"];
}