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

前端 未结 12 2129
梦毁少年i
梦毁少年i 2020-11-28 21:19

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

I am using [ .writeFilePath ] method to save an image into the Documents

12条回答
  •  孤城傲影
    2020-11-28 21:42

    For the benefit of Swift 3 beginners:

    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

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

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

提交回复
热议问题