ios 如何检查文件是否存在于 Swift 的 Documents 目录中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24181699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:51:57  来源:igfitidea点击:

How to check if a file exists in the Documents directory in Swift?

iosxcodeswift

提问by GgnDpSingh

How to check if a file exists in the Documents directory in Swift?

如何检查文件目录中的文件是否存在Swift

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.

我正在使用[ .writeFilePath ]方法将图像保存到 Documents 目录中,我想在每次启动应用程序时加载它。但是如果没有保存的图像,我有一个默认图像。

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.

但我无法理解如何使用该[ func fileExistsAtPath(_:) ]功能。有人可以举一个使用该函数的示例,其中传递了一个路径参数。

I believe I don't need to paste any code in there as this is a generic question. Any help will be much appreciated.

我相信我不需要在那里粘贴任何代码,因为这是一个通用问题。任何帮助都感激不尽。

Cheers

干杯

回答by mike.tihonchik

Swift 4.xversion

斯威夫特 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.xversion

斯威夫特 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.xversion, need to use URLByAppendingPathComponent

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")
    }

回答by PREMKUMAR

Check the below code:

检查以下代码:

Swift 1.2

斯威夫特 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

斯威夫特 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");
}

回答by vadian

Nowadays (2016) Apple recommends more and more to use the URL related API of NSURL, NSFileManageretc.

如今(2016)苹果建议越来越多使用的URL相关的API NSURLNSFileManager等等。

To get the documents directory in iOS and Swift 2use

要获取 iOS 和Swift 2 中的文档目录,请使用

let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, 
                                 inDomain: .UserDomainMask, 
                        appropriateForURL: nil, 
                                   create: true)

The try!is safe in this case because this standard directory is guaranteed to exist.

try!因为这个标准目录是保证生存在这种情况下是安全的。

Then append the appropriate path component for example an sqlitefile

然后附加适当的路径组件,例如一个sqlite文件

let databaseURL = documentDirectoryURL.URLByAppendingPathComponent("MyDataBase.sqlite")

Now check if the file exists with checkResourceIsReachableAndReturnErrorof NSURL.

现在检查文件是否存在checkResourceIsReachableAndReturnErrorof NSURL

let fileExists = databaseURL.checkResourceIsReachableAndReturnError(nil)

If you need the error pass the NSErrorpointer to the parameter.

如果您需要错误,请将NSError指针传递给参数。

var error : NSError?
let fileExists = databaseURL.checkResourceIsReachableAndReturnError(&error)
if !fileExists { print(error) }

Swift 3+:

斯威夫特 3+:

let documentDirectoryURL = try! FileManager.default.url(for: .documentDirectory, 
                                in: .userDomainMask, 
                    appropriateFor: nil, 
                            create: true)

let databaseURL = documentDirectoryURL.appendingPathComponent("MyDataBase.sqlite")

checkResourceIsReachableis marked as can throw

checkResourceIsReachable被标记为可以抛出

do {
    let fileExists = try databaseURL.checkResourceIsReachable()
    // handle the boolean result
} catch let error as NSError {
    print(error)
}

To consider only the boolean return value and ignore the error use the nil-coalescing operator

要仅考虑布尔返回值并忽略错误,请使用 nil-coalescing 运算符

let fileExists = (try? databaseURL.checkResourceIsReachable()) ?? false

回答by Mick MacCallum

It's pretty user friendly. Just work with NSFileManager's defaultManager singleton and then use the fileExistsAtPath()method, which simply takes a string as an argument, and returns a Bool, allowing it to be placed directly in the if statement.

它非常用户友好。只需使用 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!!
}

Note that the downcast to String isn't necessary in Swift 2.

请注意,在 Swift 2 中不需要向下转换为 String。

回答by Surya Kameswara Rao Ravi

An alternative/recommended Code Pattern in Swift 3would be:

Swift 3 中的替代/推荐代码模式是:

  1. Use URL instead of FileManager
  2. Use of exception handling

    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)")
        }
    }
    
  1. 使用 URL 而不是 FileManager
  2. 异常处理的使用

    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)")
        }
    }
    

回答by Lakhdeep Singh

Swift 4.2

斯威夫特 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;
        }
    }
}

Using: -

使用: -

if fileUrl.checkFileExist()
   {
      // Do Something
   }

回答by Surya Kameswara Rao Ravi

For the benefit of Swift 3beginners:

为了Swift 3初学者的利益:

  1. Swift 3 has done away with most of the NextStep syntax
  2. So NSURL, NSFilemanager, NSSearchPathForDirectoriesInDomain are no longer used
  3. Instead use URL and FileManager
  4. NSSearchPathForDirectoriesInDomain is not needed
  5. Instead use FileManager.default.urls
  1. Swift 3 取消了大部分 NextStep 语法
  2. 所以不再使用 NSURL、NSFilemanager、NSSearchPathForDirectoriesInDomain
  3. 而是使用 URL 和 FileManager
  4. 不需要 NSSearchPathForDirectoriesInDomain
  5. 而是使用 FileManager.default.urls

Here is a code sample to verify if a file named "database.sqlite" exists in application document directory:

这是一个代码示例,用于验证应用程序文档目录中是否存在名为“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)")
    }

}

回答by Rohit Sisodia

Very simple: If your path is a URL instance convert to string by 'path' method.

很简单:如果您的路径是 URL 实例,则通过 'path' 方法转换为字符串。

    let fileManager = FileManager.default
    var isDir: ObjCBool = false
    if fileManager.fileExists(atPath: yourURLPath.path, isDirectory: &isDir) {
        if isDir.boolValue {
            //it's a Directory path
        }else{
            //it's a File path
        }
    }

回答by Maurizio FIORINO

This works fine for me in swift4:

这在 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

        }


}

You can check with this call:

您可以通过此电话检查:

   if existingFile(fileName: "yourfilename") == true {

            // your code if file exists

           } else {

           // your code if file does not exist

           }

I hope it is useful for someone. @;-]

我希望它对某人有用。@;-]

回答by nastassia

works at Swift 5

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)
    }

where "userInfo"- file's name, and "sqlite3"- file's extension

其中"userInfo"- 文件名,以及"sqlite3"- 文件的扩展名