los.adrian
los.adrian

Reputation: 538

How can I convert a concrete directory path to NSURL?

I'd like to know how could I create a URL from a path String. Here my code:

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

I'd like to add only folders to the itemList array. The hasDirectoryPath is an URL method. How could i change my code to get URLs not String.

Thank you in advance for any help you can provide.

Upvotes: 1

Views: 147

Answers (1)

Martin R
Martin R

Reputation: 539685

Better use the contentsOfDirectory(at url: URL, ...) method of FileManager, that gives you an array of URLs instead of strings:

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

Upvotes: 1

Related Questions