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

前端 未结 12 2156
梦毁少年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:49

    This works fine for me in 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. @;-]

提交回复
热议问题