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?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
ikel
  • 1,790
  • 6
  • 31
  • 61
  • 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. – Leo Dabus Aug 24 '19 at 21:46
  • .path, that's why.....thx for pointing out, please edit ur answer so that I can mark it accepted – ikel Aug 24 '19 at 22:23
  • https://stackoverflow.com/questions/40642217/uiimagecontentsoffile-returning-nil-despite-file-existing-in-caches-directory/40643037 – Leo Dabus Aug 25 '19 at 00:13

0 Answers0