1

我想知道如何从路径字符串创建 URL。这是我的代码:

    let completePath = "/Volumes/MyNetworkFolder/"

    do {
        let items = try FileManager.default.contentsOfDirectory(atPath: completePath)

        for item in items {
            if item.hasDirectoryPath { //String has no member hasDirectoryPath
                itemList.append(item)
            }
        }
    } catch {
        print("Failed to read dir")
        let buttonPushed = dialogOKCancel(question: "Failed to read dir", text: "Map the network folder")
        if(buttonPushed) {
            exit(0)
        }
    }

我只想将文件夹添加到 itemList 数组中。hasDirectoryPath 是一个 URL 方法。我如何更改我的代码以获取 URL 而不是字符串。

提前感谢您提供的任何帮助。

4

1 回答 1

1

更好地使用 s 的contentsOfDirectory(at url: URL, ...)方法 FileManager,它给你一个 s 数组URL而不是字符串:

let dirPath = "/Volumes/MyNetworkFolder/"
let dirURL = URL(fileURLWithPath: dirPath)

do {
    let items = try FileManager.default.contentsOfDirectory(at: dirURL,
                                                            includingPropertiesForKeys: nil)
    for item in items {
        if item.hasDirectoryPath {
            // item is a URL
            // item.path is its file path as a String
            // ...
        }
    }
} catch {
    print("Failed to read dir:", error.localizedDescription)
}
于 2018-09-21T11:49:10.467 回答