Check if NSURL is a directory

alex picture alex · Jun 13, 2014 · Viewed 15k times · Source

While using Swift I want to check if an NSURL location is a directory. With Objective-C this is not a problem and working find, but when I convert the code to Swift I run into a runtime error.

Maybe someone can point me in the right direction?

import Foundation

let defaultManager = NSFileManager.defaultManager()
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let localDocumentURLs = defaultManager.contentsOfDirectoryAtURL(documentsDirectory,
includingPropertiesForKeys: nil, options: .SkipsPackageDescendants, error: nil) as NSURL[]

for url in localDocumentURLs {
    var isError: NSError? = nil
    var isDirectory: AutoreleasingUnsafePointer<AnyObject?> = nil
    var success: Bool = url.getResourceValue(isDirectory, forKey: NSURLIsDirectoryKey, error: &isError)
}

Answer

vadian picture vadian · Apr 23, 2017

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);