如何检查Swift
中的Documents目录中是否存在文件?
我正在使用[ .writeFilePath ]
方法将图像保存到Documents目录中,我想在每次启动应用程序时加载它。但是如果没有保存的图像,我有一个默认图像。
但我无法理解如何使用[ func fileExistsAtPath(_:) ]
功能。有人可以举例说明如何使用带有路径参数的函数。
我相信我不需要在那里粘贴任何代码,因为这是一个通用的问题。任何帮助将不胜感激。
干杯
答案 0 :(得分:201)
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")
}
答案 1 :(得分:33)
检查以下代码:
Swift 1.2
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let getImagePath = paths.stringByAppendingPathComponent("SavedFile.jpg")
let checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath(getImagePath))
{
println("FILE AVAILABLE");
}
else
{
println("FILE NOT AVAILABLE");
}
Swift 2.0
let paths = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let getImagePath = paths.URLByAppendingPathComponent("SavedFile.jpg")
let checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath("\(getImagePath)"))
{
print("FILE AVAILABLE");
}
else
{
print("FILE NOT AVAILABLE");
}
答案 2 :(得分:24)
如今(2016)Apple建议越来越多地使用NSURL
,NSFileManager
等与网址相关的API。
要获取iOS中的文档目录和 Swift 2 ,请使用
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask,
appropriateForURL: nil,
create: true)
try!
在这种情况下是安全的,因为这个标准目录保证存在。
然后附加适当的路径组件,例如sqlite
文件
let databaseURL = documentDirectoryURL.URLByAppendingPathComponent("MyDataBase.sqlite")
现在检查文件是否存在,checkResourceIsReachableAndReturnError
为NSURL
。
let fileExists = databaseURL.checkResourceIsReachableAndReturnError(nil)
如果您需要错误,请将NSError
指针传递给参数。
var error : NSError?
let fileExists = databaseURL.checkResourceIsReachableAndReturnError(&error)
if !fileExists { print(error) }
Swift 3 +:
let documentDirectoryURL = try! FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
let databaseURL = documentDirectoryURL.appendingPathComponent("MyDataBase.sqlite")
checkResourceIsReachable
被标记为可以投掷
do {
let fileExists = try databaseURL.checkResourceIsReachable()
// handle the boolean result
} catch let error as NSError {
print(error)
}
要仅考虑布尔返回值并忽略错误,请使用nil-coalescing运算符
let fileExists = (try? databaseURL.checkResourceIsReachable()) ?? false
答案 3 :(得分:15)
它非常友好。只需使用NSFileManager的defaultManager单例,然后使用fileExistsAtPath()
方法,它只需要一个字符串作为参数,并返回一个Bool,允许它直接放在if语句中。
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentDirectory = paths[0] as! String
let myFilePath = documentDirectory.stringByAppendingPathComponent("nameOfMyFile")
let manager = NSFileManager.defaultManager()
if (manager.fileExistsAtPath(myFilePath)) {
// it's here!!
}
请注意,在Swift 2中不需要向下转换为String。
答案 4 :(得分:5)
Swift 3 中的替代/推荐代码模式将是:
使用异常处理
func verifyIfSqliteDBExists(){
let docsDir : URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dbPath : URL = docsDir.appendingPathComponent("database.sqlite")
do{
let sqliteExists : Bool = try dbPath.checkResourceIsReachable()
print("An sqlite database exists at this path :: \(dbPath.path)")
}catch{
print("SQLite NOT Found at :: \(strDBPath)")
}
}
答案 5 :(得分:4)
为了 Swift 3 初学者的利益:
这是一个代码示例,用于验证应用程序文档目录中是否存在名为“database.sqlite”的文件:
func findIfSqliteDBExists(){
let docsDir : URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dbPath : URL = docsDir.appendingPathComponent("database.sqlite")
let strDBPath : String = dbPath.path
let fileManager : FileManager = FileManager.default
if fileManager.fileExists(atPath:strDBPath){
print("An sqlite database exists at this path :: \(strDBPath)")
}else{
print("SQLite NOT Found at :: \(strDBPath)")
}
}
答案 6 :(得分:2)
很简单: 如果您的路径是通过'路径'转换为字符串的网址实例方法
import cv2
import numpy as np
img = cv2.imread('input.png',0)
kernel = np.ones((5,5), np.uint8)
dilation = cv2.dilate(img,kernel,iterations = 5)
cv2.imwrite('result.png', dilation)
答案 7 :(得分:1)
Swift 4 示例:
var filePath: String {
//manager lets you examine contents of a files and folders in your app.
let manager = FileManager.default
//returns an array of urls from our documentDirectory and we take the first
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
//print("this is the url path in the document directory \(String(describing: url))")
//creates a new path component and creates a new file called "Data" where we store our data array
return(url!.appendingPathComponent("Data").path)
}
我将支票放入了在viewDidLoad中调用的loadData函数中。
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
然后我在下面定义了loadData。
func loadData() {
let manager = FileManager.default
if manager.fileExists(atPath: filePath) {
print("The file exists!")
//Do what you need with the file.
ourData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! Array<DataObject>
} else {
print("The file DOES NOT exist! Mournful trumpets sound...")
}
}
答案 8 :(得分:0)
您必须添加&#34; /&#34;在文件名之前斜杠,或者你得到像&#34; ... / DocumentsFilename.jpg&#34;
这样的路径答案 9 :(得分:0)
这对swift4来说对我来说很好:
func existingFile(fileName: String) -> Bool {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("\(fileName)") {
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath)
{
return true
} else {
return false
}
} else {
return false
}
}
您可以通过以下电话进行确认:
if existingFile(fileName: "yourfilename") == true {
// your code if file exists
} else {
// your code if file does not exist
}
我希望它对某人有用。 @;-]
答案 10 :(得分:0)
Swift 4.2
extension URL {
func checkFileExist() -> Bool {
let path = self.path
if (FileManager.default.fileExists(atPath: path)) {
print("FILE AVAILABLE")
return true
}else {
print("FILE NOT AVAILABLE")
return false;
}
}
}
使用:-
if fileUrl.checkFileExist()
{
// Do Something
}
答案 11 :(得分:0)
以 Swift 5
运行 do {
let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileUrl = documentDirectory.appendingPathComponent("userInfo").appendingPathExtension("sqlite3")
if FileManager.default.fileExists(atPath: fileUrl.path) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
} catch {
print(error)
}
其中"userInfo"
-文件名,"sqlite3"
-文件扩展名
答案 12 :(得分:0)
extension FileManager {
class func fileExists(filePath: String) -> Bool {
var isDirectory = ObjCBool(false)
return self.default.fileExists(atPath: filePath, isDirectory: &isDirectory)
}
}