Search code examples
objective-ciosios5nsfilemanager

Unable to copy file from bundle to Documents directory, why does fileExistsAtPath return error?


I'm using the following snippet of code to attempt to copy a file from my application resources directory into the Documents area. I have used the below from the PocketOCR project on Github :

// Set up the tessdata path. This is included in the application bundle
    // but is copied to the Documents directory on the first run.
    NSString *dataPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"tessdata"];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSLog(@"Datapath is %@", dataPath);
    // If the expected store doesn't exist, copy the default store.
    if (![fileManager fileExistsAtPath:dataPath ]) {
        NSLog(@"File didn't exist at datapath...");
        // get the path to the app bundle (with the tessdata dir)
        NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
        NSString *tessdataPath = [bundlePath stringByAppendingPathComponent:@"tessdata"];
        if (tessdataPath) {
            [fileManager copyItemAtPath:tessdataPath toPath:dataPath error:NULL];
        }
    }

This is the output I get from invoking the above :

2012-06-06 14:53:42.607 MyApp[1072:707] Datapath is /var/mobile/Applications/9676D920-D6D1-4F86-9177-07CC3247A124/Documents/tessdata Error opening data file /var/mobile/Applications/9676D920-D6D1-4F86-9177-07CC3247A124/Documents/tessdata/eng.traineddata

I have the eng.traineddata file located in my xcode project like so

It appears that the Error is being reported when attempting to check if fileExistsAtPath, I wouldn't expect this to throw an error, but to either return YES or NO.

Is there an easier way to copy the eng.traineddata file across, or have I made a mistake which can be corrected here?

I have the eng.traineddata file located in my xcode project like so


Solution

  • NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSString *dataPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"tessdata"];
    NSLog(@"Datapath is %@", dataPath);
    
    // If the expected store doesn't exist, copy the default store.    
        if ([fileManager fileExistsAtPath:dataPath] == NO)
        {
            NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:@"eng" ofType:@"traineddata"];
            [fileManager copyItemAtPath:tessdataPath toPath:dataPath error:&error];
    
        }
    
    
    -(NSString*) applicationDocumentsDirectory{
        // Get the documents directory
        NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docsDir = [dirPaths objectAtIndex:0];
        return docsDir;
    }