如何返回当前目录(“。”),父目录(“..”)的URL

时间:2017-02-16 12:53:40

标签: ios swift

我想在tableView中列出用户文档目录的所有内容,包括当前目录(“。”)和父目录(“..”)。

它工作正常,但它不显示当前和父目录。

出于测试原因,我编写了以下代码:

if let enumerator = fileManager.enumerator(at: URL(string: documentsPath)!, includingPropertiesForKeys: nil, options: [], errorHandler: nil)
        {
            for item in enumerator{
                print(item)
            }
        }

那么如何列出当前和父目录?

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

你可以试试这个,

<强>夫特

var pathStr: String = "/path/abc"
let fileURL: URL = URL(fileURLWithPath: pathStr)
let parentUrl = fileURL.deletingLastPathComponent()
print("Parent Directory url : \(parentUrl)")

注意:没关系swift语法。

<强>目标C

NSString *pathStr = @"/path/abc";
NSURL *parentUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [pathStr stringByDeletingLastPathComponent]]];
NSLog(@"Parent Directory url: %@",parentUrl);

答案 1 :(得分:0)

我知道这很旧,但是如果有人在浏览;您可以使用URLResourceKey来获取以下信息:

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

    }

}