1

I have been trying to work with files and folders using swift

I'm using code from listing all files in a folder recursively with swift

let url = URL(fileURLWithPath: "/path/to/directory")
var files = [URL]()
if let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) {
    for case let fileURL as URL in enumerator {
        do {
            let fileAttributes = try fileURL.resourceValues(forKeys:[.isRegularFileKey])
            if fileAttributes.isRegularFile! {
                files.append(fileURL)
            }
        } catch { 
            print(error, fileURL) 
        }
    }
    print(files)
}

It works fine when printing list of files, but the result contains file:/// prefix and if file path or file name contains a white space, the result will add "%20", this is causing some issues

for example: file $_59 (7).jpeg, from above code, the path is file:///Users/kkkk/folder/$_59%20(7).jpeg

when reading it

let data = try Data(contentsOf: URL(fileURLWithPath: filePath))

got error: Error Domain=NSCocoaErrorDomain Code=260 "The file “$_59%20(7).jpeg” couldn’t be opened because there is no such file."

I removed prefix file:// so now the path I get is /Users/kkkk/folder/$_59%20(7).jpeg,

As I test, I found that it works if I manually enter /Users/kkkk/folder/$_59 (7).jpeg

So any idea how i can get real path /Users/kkkk/folder/$_59 (7).jpeg?

3
  • Please edit your question and show how you are getting a string from your URL. Note that you should work with URL instead of paths. Btw looks like you are using the URL .absoluteString (includes the URL schema "file://") when you should be using its .path property. Commented Aug 24, 2019 at 21:46
  • .path, that's why.....thx for pointing out, please edit ur answer so that I can mark it accepted Commented Aug 24, 2019 at 22:23
  • stackoverflow.com/questions/40642217/… Commented Aug 25, 2019 at 0:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.