Check if NSURL is a directory

In iOS 9.0+ and macOS 10.11+ there is a property in NSURL / URL

Swift:

var hasDirectoryPath: Bool { get }

Objective-C:

@property(readonly) BOOL hasDirectoryPath;

However this is only reliable for URLs created with the FileManager API which ensures that the string path of a dictionary ends with a slash.

For URLs created with custom literal string paths reading the resource value isDirectory is preferable

Swift:

let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false

Objective-C:

NSNumber *isDirectory = nil;
[url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
NSLog(@"%i", isDirectory.boolValue);

Swift 3

extension URL {
    var isDirectory: Bool {
        let values = try? resourceValues(forKeys: [.isDirectoryKey])
        return values?.isDirectory ?? false
    }
}

Tags:

Swift

Nsurl