Search code examples
iosnsfilemanager

Error checking for subdirectory of Documents directory in IOS


My app needs to create a subdirectory of the Documents directory. The code below returns the directory URL. First time through it creates the directory, but fails next time because fileExistsAtPath: claims the directory still doesn't exist. I know it exists though because I have set the bundle to make files visible in iTunes and I can see it in iTunes. Any idea what I'm doing wrong?

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager]   URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSURL *)applicationSubDirectory
{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSURL *docDir = [self applicationDocumentsDirectory];
    docDir = [docDir URLByAppendingPathComponent:@"Sub" isDirectory:YES];
    NSString *docDirPath = [docDir absoluteString];
    BOOL isFolder = YES;

    if(!([manager fileExistsAtPath:docDirPath isDirectory:&isFolder] && isFolder))    {
        NSError *error = nil;
        BOOL ret = [manager createDirectoryAtURL:docDir withIntermediateDirectories:NO attributes:nil error:&error];
        if(!ret) {
            NSLog(@"ERROR app support: %@", error);
            abort();
        }
    }
    return docDir;
}

Solution

  • You want to use path instead of absoluteString The former returns the full url absolute path, something like "file:///..." while the latter only returns the file path.

    NSString *docDirPath = [docDir path];
    

    So, since you're looking for a file with the path "file:///...." which will never exist, the check always fails. When you go to create the directory, you create it with the URL, so it works.