NSFileManager.defaultManager (). FileExistsAtPath returns false instead of true

How is this possible?

let exists = NSFileManager.defaultManager().fileExistsAtPath(path.absoluteString) print("exists: \(exists)") //false 

This is path.absoluteString

 //file:///Users/kuna/Library/Developer/CoreSimulator/Devices/92BD140D-5C14-43C4-80D6-904BB9594ED6/data/Containers/Data/Application/5B818832-BB19-4047-A7F8-1487F36868D6/Documents/wishlists/68/147/128/IMG_0006.PNG 

And you can see that he is where he should be:

enter image description here

What's happening?

+27
ios swift nsfilemanager
Dec 07 '15 at 13:56 on
source share
2 answers

(The code in this answer has been updated for Swift 3 and later.)

Obviously your path variable is NSURL (describing the file path). To get the path as a string, use the path property, not absoluteString :

 let exists = FileManager.default.fileExists(atPath: path.path) 

absoluteString returns the URL in string format, including the file: scheme file:

Example:

 let url = URL(fileURLWithPath: "/path/to/foo.txt") // This is what you did: print(url.absoluteString) // Output: file:///path/to/foo.txt // This is what you want: print(url.path) // Output: /path/to/foo.txt 
+65
07 Dec '15 at 2:02
source share
— -

If you want to check if the path exists, you must check the path

 let url = NSURL(string: "balabala") let path = url?.path //Check path 
+2
Dec 07 '15 at 2:02
source share



All Articles