Objective-C contentsOfDirectoryAtURL need filenames instead complete path
-
07-07-2021 - |
Question
I´m using this piece of code to get the files contained in folder pathTo_Folder. What I get is something like this: "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Tech-2.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Tech-3.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Tech-4.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-1.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-2.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-3.jpg", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-4.png", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-5.png", "file://localhost/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen/Terra-6.jpg"
I wonder if there is a way to get only the filename without the containing folder like "Tech-2.jpg"
NSString *pathTo_Folder = @"/Users/ronny/DEV/0200-ObjC4/ModernTimes/DrawingFun/linen";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *theFiles = [fileManager contentsOfDirectoryAtURL:
[NSURL fileURLWithPath:pathTo_Folder]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLNameKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
Greetings from Switzerland, Ronald Hofmann
Solution
for( NSURL* fileURL in theFiles ) {
NSString* filename = [fileURL lastPathComponent];
// do things with the filename
}
As per the comments, if you just want the filenames:
// Note, this is not very efficient, and it's especially inefficient if
// you then go ahead and iterate the resultant array
NSArray* filenames = [theFiles valueForKeyPath:@"lastPathComponent"];
OTHER TIPS
NSURL has a method lastPathComponent
that does exactly what you need.