Krunal
Krunal

Reputation: 6490

Unable to create folder inside document directory

I developed iPhone app in which i got stuck at one point,

What i want to do is, I want to copy my Database from bundle to folder inside document directory

When i try to create folder inside DocDir it doesn't getting created and it shows error,

Failed to create MyDB.sql file with message 'The operation couldn’t be completed. (Cocoa error 4.)

Here is my code snippet,

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [[paths objectAtIndex:0] stringByAppendingString:@"/NewFolder/"];

    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"MyDB.sql"];
    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if(!success) {

        NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"MyDB" ofType:@"sql"];

        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success)
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }

Where i am doing mistake? please help

Thanks in advance.

Upvotes: 1

Views: 2974

Answers (1)

Ashish Kakkad
Ashish Kakkad

Reputation: 23902

Try to create directory by following code, may you get help..

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/YourFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])//Check
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Will Create folder

Upvotes: 4

Related Questions