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/39815883/

相关文章:

objective-c - 使用自定义方法将自定义对象添加到数组 Swift 问题

iphone - 检查 bundle 中是否存在图像 - iPhone

Iphone 将 url 标记为不安全

iphone - 关于以编程方式创建 UITextField 的问题

ios - 在 Swift 中显示 NLTokenizer 的索引、标记

objective-c - stringByReplacingOccurrence 不替换字符串

ios - 在应用程序启动时获取包文件引用/路径

ios - 尝试加粗 UIButton 的 titleLabel 以响应在 iOS 中调用的委托(delegate)方法

iOS:如何在没有 "Potential leak"警告的情况下将 ABAddressBookRef 存储在属性中?

ios - 为什么我的 GPA Double 值在 Swift 中不能正常工作?