Search code examples
objective-cmacosfilefilesystemsnsfilemanager

Mac OS: how to determine path is file or directory


I have a path and I want to know, is this directory or a file. Pretty simple, but I have a problem. Here's my path:

NSString *file = @"file://localhost/Users/myUser/myFolder/TestFolder/";

or

NSString *file = @"file://localhost/Users/myUser/myFolder/my_test_file.png";

Here is my code:

BOOL isDir;


// the original code from apple documentation: 
// if ([fileManager fileExistsAtPath:file isDirectory:&isDir] && isDir)
// but even my if returns me "not ok" in log

if([[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir])
{

     NSLog(@"directory");
}
else
{
     NSLog(@"not ok");
}

files and dirs on this pathes are exists and they are ok. But I thinks problem could be in it. But I don't know why. Help me with this please.

By the way, I get path from another method:

   NSArray *contentOfMyFolder = [[NSFileManager defaultManager]
                contentsOfDirectoryAtURL:urlFromBookmark
              includingPropertiesForKeys:@[NSURLContentModificationDateKey, NSURLLocalizedNameKey]
                                 options:NSDirectoryEnumerationSkipsHiddenFiles
                                   error:nil];

after this in for loop, I get items that stored in array contentOfMyFolder and get path like this:

 for (id item in contentOfMyFolder) {
     NSString *path = [item absoluteString]; 
 }

I thinks this is perfectly valid path for method fileExistsAtPath:(NSString *)path isDirectory:(BOOL)isDir

Where the problem could hide?!


Solution

  • The problem is here:

    NSString *path = [item absoluteString];
    

    because that creates a string representation of the URL, such as

    file://localhost/Users/myUser/myFolder/TestFolder/
    

    and that is not what fileExistsAtPath: expects. What you need is the path method to convert the URL to a path:

    for (NSURL *item in contentOfMyFolder) {
        NSString *path = [item path];
        BOOL isDir;
        if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
            if (isDir) {
                NSLog(@"%@ is a directory", path);
            } else {
                NSLog(@"%@ is a file", path);
            }
        } else {
            NSLog(@"Oops, %@ does not exist?", path);
        }
    }
    

    Alternatively, you can ask the URL for its "directory property":

    for (NSURL *item in contentOfMyFolder) {
        NSNumber *isDir;
        NSError *error;
        if ([item getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:&error]) {
            if ([isDir boolValue]) {
                NSLog(@"%@ is a directory", item);
            } else {
                NSLog(@"%@ is a file", item);
            }
        } else {
            NSLog(@"error: %@", error);
        }
    }