Reputation: 1679
I want to list all the contents of the user's document directory in a tableView including the current directory (“.”) and parent directory (“..”).
Its working fine but it does not show the current and parent directory.
For testing reasons i wrote the following code:
if let enumerator = fileManager.enumerator(at: URL(string: documentsPath)!, includingPropertiesForKeys: nil, options: [], errorHandler: nil)
{
for item in enumerator{
print(item)
}
}
So how can i list the current and parent directory?
Any help is highly appreciated !
Upvotes: 3
Views: 2880
Reputation: 11
I know this is old, but in case someone is browsing; you can use the URLResourceKey to get this information:
func simpleReadDirectoryClean(path: String) {
//where path looks like "FolderInMyBundle/Docs"
let fm = FileManager.default
let resourceKeys : [URLResourceKey] = [.nameKey, .isDirectoryKey, .parentDirectoryURLKey]
let bundleURL = Bundle.main.resourceURL?.appendingPathComponent(path)
let enumerator = fm.enumerator(at: bundleURL!, includingPropertiesForKeys: resourceKeys)!
for case let item as URL in enumerator {
let resourceInfo = try? item.resourceValues(forKeys: Set(resourceKeys))
print("-------------- under folder \(path)")
print("******\(resourceInfo!.isDirectory! ? "Folder" : "File"): \(item.lastPathComponent)")
print("Parent folder name: \(String(describing: resourceInfo!.parentDirectory?.lastPathComponent))")
print("Parent folder full path: \(String(describing: resourceInfo!.parentDirectory))")
}
}
Upvotes: 1
Reputation: 2189
You can try this,
Swift
var pathStr: String = "/path/abc"
let fileURL: URL = URL(fileURLWithPath: pathStr)
let parentUrl = fileURL.deletingLastPathComponent()
print("Parent Directory url : \(parentUrl)")
Note: Nevermind swift syntax.
Objective-C
NSString *pathStr = @"/path/abc";
NSURL *parentUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [pathStr stringByDeletingLastPathComponent]]];
NSLog(@"Parent Directory url: %@",parentUrl);
Upvotes: 0