Andrey Chernukha
Andrey Chernukha

Reputation: 21808

Can't write to document directory

I'm trying to copy a json file from the application bundle to the Document directory, but surprisingly i'm not able to do that. Here's the code:

NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [array lastObject];
NSString *path   = [docDir stringByAppendingPathExtension:@"themes.json"];

if (![[NSFileManager defaultManager] fileExistsAtPath:path])
   {
     NSString *themesPath = [[NSBundle mainBundle] pathForResource:@"themes" ofType:@"json"];
     NSError  *error      = nil;

    [[NSFileManager defaultManager] copyItemAtPath:themesPath toPath:path error:&error];

     if (error)
        NSLog(@"Error %@", error);
  }

It produces the following error:

Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x194a0e90 {NSSourceFilePathErrorKey=/var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Frinder.app/themes.json, NSUserStringVariant=( Copy ), NSFilePath=/var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Frinder.app/themes.json, NSDestinationFilePath=/var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Documents.themes.json, NSUnderlyingError=0x194a0400 "The operation couldn’t be completed. Operation not permitted"}

After a search i've found this question and tried to modify my code as follows:

 if (![[NSFileManager defaultManager] fileExistsAtPath:path])
    {
       NSString *themesPath = [[NSBundle mainBundle] pathForResource:@"themes" ofType:@"json"];
       NSData   *data       = [NSData dataWithContentsOfFile:themesPath];

       BOOL success =  [[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];

       if (!success)
          NSLog(@"Fail"); 
    }

but it doesn't work either. success variable is NO. The last thing i tried was:

[data writeToFile:path atomically:YES];

but still in vain. it returns NO.

I need to note that the issue arises on a device only. On a simulator it works all right. Can anybody give me a clue?

Upvotes: 2

Views: 3879

Answers (1)

rckoenes
rckoenes

Reputation: 69459

The first example is correct on one thing:

[docDir stringByAppendingPathExtension:@"themes.json"];

should be:

[docDir stringByAppendingPathComponent:@"themes.json"];

This becomes clear we you read the error message, you see that it tries to write the file to /var/mobile/Applications/ACED3EF9-B0D8-49E8-91DE-37128357E509/Documents.themes.json. Notice that there a . where there should be a /.

The stringByAppendingPathExtension: is used for adding a extension to a file, jpg, txt, html,.....

stringByAppendingPathComponent will add a file to a path, by adding the correct directory separator, you case /.

You second example will definitely fail since the app bundle is readonly.

Upvotes: 4

Related Questions