如何检查Swift中Documents文件目录中是否存在文件? [英] How to check if a file exists in the Documents directory in Swift?
问题描述
如何检查 Swift
中的Documents目录中是否存在文件?
How to check if a file exists in the Documents directory in Swift
?
我正在使用 [。writeFilePath]
将图像保存到Documents目录的方法,我想在每次启动应用程序时加载它。但是如果没有保存的图像,我有一个默认图像。
I am using [ .writeFilePath ]
method to save an image into the Documents directory and I want to load it every time the app is launched. But I have a default image if there is no saved image.
但是我无法理解如何使用 [func fileExistsAtPath( _ :)]
功能。有人可以给出一个使用带有路径参数的函数的例子。
But I just cant get my head around how to use the [ func fileExistsAtPath(_:) ]
function. Could someone give an example of using the function with a path argument passed into it.
我相信我不需要在那里粘贴任何代码,因为这是一个通用的题。任何帮助将不胜感激。
I believe I don't need to paste any code in there as this is a generic question. Any help will be much appreciated.
干杯
推荐答案
Swift 4.x 版本
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
} else {
print("FILE PATH NOT AVAILABLE")
}
Swift 3.x 版本
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("nameOfFileHere").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
Swift 2.x 版本,需要使用 URLByAppendingPathComponent
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
这篇关于如何检查Swift中Documents文件目录中是否存在文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!