Search code examples
objective-cfiledirectorynsurlnsfilemanager

How to find out if the NSURL is a directory or not


I have a NSURL object. It has address of a filesystem element, it is either a file or a directory. I want to be able to tell if the NSURL is a directory or a file.

I have already tried this, which doesn"t seem to work!

NSURL * temp ....... ;// it is initialized and has a valid value 
CFURLRef xx = (CFURLRef)CFBridgingRetain(temp);
if(CFURLHasDirectoryPath(xx)) NSLog(@"was a file");
else NSLog(@"was a folder");

Solution

  • NSNumber *isDirectory;
    
    // this method allows us to get more information about an URL. 
    // We're passing NSURLIsDirectoryKey as key because that's the info we want to know.
    // Also, we pass a reference to isDirectory variable, so it can be modified to have the return value
    BOOL success = [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
    
    // If we could read the information and it's indeed a directory
    if (success && [isDirectory boolValue]) {
        NSLog(@"Congratulations, it's a directory!");
    } else {
        NSLog(@"It seems it's just a file.");
    }