NSFileManager.defaultManager()。fileExistsAtPath返回false而不是true [英] NSFileManager.defaultManager().fileExistsAtPath returns false instead of true

查看:949
本文介绍了NSFileManager.defaultManager()。fileExistsAtPath返回false而不是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

你可以看到它应该在哪里:

And you can see it is there where it should be:

发生了什么?

推荐答案

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

显然您的 path 变量是 NSURL (描述文件路径)。要将路径作为
a字符串,请使用路径属性,而不是 absoluteString

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 以字符串格式返回URL,包括
文件:计划等。

absoluteString returns the URL in a string format, including the file: scheme etc.

示例:

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

这篇关于NSFileManager.defaultManager()。fileExistsAtPath返回false而不是true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆