这怎么可能?
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
以字符串格式返回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