ios - NSFileManager.defaultManager().fileExistsAtPath 返回 false 而不是 true

标签 ios swift nsfilemanager

这怎么可能?

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

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

enter image description here

这是怎么回事?

最佳答案

(此答案中的代码已针对 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

关于ios - NSFileManager.defaultManager().fileExistsAtPath 返回 false 而不是 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34135305/

相关文章:

ios - 在自定义 tableviewcell 中更改 UIImage

ios - 创建一个清晰的 blurView

json - 将复杂 JSON 中的每个值提取到 Swift 中的数组中

swift - 是否有任何简写方式来编写 CGPoint、CGRect 等?

ios - iOS 中的路径和 URL 有什么区别?

ios - 区分手指触摸和 Apple Pencil 触摸

ios substr 从结束

swift - 将 Int 转换为 Bool

ios - NSFileManager 删除项目路径 : error: did not actually free disk space

ios FileManager 在重建应用程序时丢失存储的数据