49

How is it 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 it is there where it should be:

enter image description here

What is going on?

Bartłomiej Semańczyk
  • 52,820
  • 43
  • 206
  • 318
  • can you print the document directory func printDocument() { let pathToFile = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.CachesDirectory , .UserDomainMask, true)[0] do { let namesOfFile = try Manager.contentsOfDirectoryAtPath(pathToFile) for name in namesOfFile { print("name : \(name)") } }catch let error as NSError { print("print : \(error)") } } – kholl Dec 07 '15 at 14:01
  • so apparently the file does not exist . How do you Save it – kholl Dec 07 '15 at 14:09

2 Answers2

120

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

Apparently your path variable is a NSURL (describing a 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 a string format, including the file: scheme etc.

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
Martin R
  • 488,667
  • 78
  • 1,132
  • 1,248
5

If you want to check if a path exist,you should check path

let url = NSURL(string: "balabala")

let path = url?.path
//Check path
Leo
  • 23,601
  • 9
  • 64
  • 89
  • This is the right answer and you got +1 but you should be more clear. if (FileManager.default.fileExists(atPath: url?.path.path)) – Numan Karaaslan Nov 04 '17 at 17:16