Swift 3.0 FileManager.fileExists(atPath :)始终返回false [英] Swift 3.0 FileManager.fileExists(atPath:) always return false
本文介绍了Swift 3.0 FileManager.fileExists(atPath :)始终返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用方法.fileExists(atPath:)
来判断文件在文件系统中是否存在时,该方法总是向我返回false.我检查了文件系统,发现文件确实存在.这是我的代码:
When I use method .fileExists(atPath:)
to judge whether the file is exist in file system, the method always return false to me. I checked the file system and the file do exist. Here is my code:
let filePath = url?.path
var isDir : ObjCBool = false
if(self.fileManager.fileExists(atPath: filePath!, isDirectory: &isDir)){
let result = NSData(contentsOfFile: filePath!)
}
或
let filePath = url?.path
if(self.fileManager.fileExists(atPath: filePath!)){
let result = NSData(contentsOfFile: filePath!)
}
if子句将始终被跳过.
the if clause will always be skipped.
推荐答案
我假设您的url
是URL
类型.如果是这样,请尝试以下方法:
I assume your url
is an URL
type. If so try this out:
let filePath = url?.path // always try to work with URL when accessing Files
if(FileManager.default.fileExists(atPath: filePath!)){ // just use String when you have to check for existence of your file
let result = NSData(contentsOf: url!) // use URL instead of String
}
说够了,您应该像这样更改实现:
Saying enough, you should change your implementation like this:
if(FileManager.default.fileExists(atPath: (url?.path)!)){ // just use String when you have to check for existence of your file
let result = NSData(contentsOf: url!) // use URL instead of String
}
1
还有更好的方法,您可以将其称为快速方法(:D).您无需明确检查文件是否存在.
There is even more better way, you can call it swift-way (:D). You don't have to explicitly check for file existence.
guard let result = NSData(contentsOf: fileURL) else {
// No data in your fileURL. So no data is received. Do your task if you got no data
// Keep in mind that you don't have access to your result here.
// You can return from here.
return
}
// You got your data successfully that was in your fileURL location. Do your task with your result.
// You can have access to your result variable here. You can do further with result constant.
print(result)
这篇关于Swift 3.0 FileManager.fileExists(atPath :)始终返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文