【问题标题】:How can I convert a concrete directory path to NSURL?如何将具体的目录路径转换为 ​​NSURL?
【发布时间】:2018-09-21 11:40:25
【问题描述】:

我想知道如何从路径字符串创建 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 而不是字符串。

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

【问题讨论】:

标签: ios swift swift4.2


【解决方案1】:

最好使用contentsOfDirectory(at url: URL, ...) 方法 FileManager,它为您提供URLs 的数组,而不是 字符串:

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

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 2012-01-25
    • 2011-10-20
    • 1970-01-01
    • 2013-04-23
    • 2014-05-04
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多