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");
If you know the file URL has been standardized, then you can test for a trailing slash.
-URLByStandardizingPath
will standardize a file URL including ensuring a trailing slash if the path is a directory.Here is a test which shows
-URLByStandardizingPath
adding the trailing slash:As you can see,
[[[directoryURL URLByStandardizingPath] absoluteString] hasSuffix:@"/"]
is the test.Starting [iOS 9, macOS 10.11, tvOS 9.0, watchOS 2.0], there is
hasDirectoryPath
:With Swift 5, you can check if a URL path represents a directory or a regular file using one of the following macOS Playground sample codes.
#1. Using
URL
'shasDirectoryPath
property#2. Using
Filemanager
'sattributesOfItem(atPath:)
method#3. Using
URLResourceValues
#4. Using
FileManager
'sfileExists(atPath:isDirectory:)
Starting iOS 8, in Swift 3, there is
isDirectory
: