NSFileManager.defaultManager().fileExistsAtPath returns false 而不是 true

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

怎么可能?

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

这是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

你可以看到它就在它应该在的地方:

这是怎么回事?

(此答案中的代码已针对 Swift 3 及更高版本更新。)

显然您的 path 变量是 NSURL(描述文件路径)。获取路径为 一个字符串,使用 path 属性,而不是 absoluteString:

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

absoluteString returns URL 字符串格式,包括 file: 方案等

示例:

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

如果你想检查路径是否存在,你应该检查路径

let url = NSURL(string: "balabala")

let path = url?.path
//Check path