20

i am using the code below to save an image in the NSDocumentDirectory

-(BOOL)saveImage:(UIImage *)image name:(NSString *)name{

    NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString *path = [NSString pathWithComponents:[NSArray arrayWithObjects:dir, name, nil]];

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

    if (!ok) {
        NSLog(@"Error creating file %@", path);
    } 
    else {
        NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
        [myFileHandle writeData:UIImagePNGRepresentation(image)];
        [myFileHandle closeFile];
    }
    return ok;
}

the name is usually the url of where the image was downloaded.

is there a constraint on the length of the file name? you know sometimes urls may be super long...

thank you

astazed
  • 649
  • 1
  • 10
  • 24

1 Answers1

35

Taking a look at the PATH_MAX constant in syslimits.h:91

... 
#define PATH_MAX         1024   /* max bytes in pathname */
...

You can test this yourself by doing :

NSLog(@"%i", PATH_MAX);

just to make sure.

deanWombourne
  • 38,189
  • 13
  • 98
  • 110
  • 21
    It's also worth noting the length of the filename component of a path - in the same header `#define NAME_MAX 255`. – petert Jul 05 '11 at 12:02
  • This should be included in the answer – Minimi Dec 23 '16 at 22:46
  • 1
    In practise it may be wise to stay somewhat below PATH_MAX for paths to intra-app resources according to [this post](https://deciphertools.com/blog/2014_10_01_beware_of_long_pathnames/). It suggests 932 characters as a working maximum, as apparently the use of intermediate directories during an iTunes/iCloud backup operation can cause the total path length to exceed PATH_MAX, resulting in failure to backup/restore your app. – user2067021 Jul 14 '17 at 07:22
  • 1
    @user2067021 Thanks for sharing that post! Just one clarification after clicking/reading through your linked post: the recommended working maximum is actually PATH_MAX - 7, or 1017. The 932 number is characters in the filename after the app sandbox, which is typically 85. So according to that, it should be safe to use PATH_MAX - 7 or 1017 to maintain support for iCloud backups. – Thompsonmachine Jul 13 '19 at 00:29