问题描述
如何在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 目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!