Search code examples
iosios6nsfilemanager

Do we need to create subfolders in Documents before calling a writeToFile with a path that contains new folder?


I am trying to write to the following path:

        NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *storePath = [docDir stringByAppendingPathComponent:@"/newfolder/test.jpg"];

        NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
        BOOL saved = [data writeToFile:storePath atomically:NO];
        NSLog(@"%c", saved);

Now, nothing gets printed and I can't see the file in my simulator. Is it because "newfolder" folder within the Documents main folder is not created yet. If so, is there a way to create it if it is not there yet?

Thanks!


Solution

  • Yes, you must make sure the folder is created first. Use NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error: passing in the path to the folder you wish to create (not the file you are trying to write).

    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *storePath = [docDir stringByAppendingPathComponent:@"newfolder/test.jpg"];
    
    [[NSFileManager defaultManager] createDirectoryAtPath:[storePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
    

    You should check the return value of these methods and handle any failures.