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

前端 未结 12 2098
梦毁少年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. @;-]

    0 讨论(0)
  • 2020-11-28 21:54

    Swift 4.x version

        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 version

        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 version, need to use 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")
        }
    
    0 讨论(0)
  • 2020-11-28 21:54

    You must add a "/" slash before filename, or you get path like ".../DocumentsFilename.jpg"

    0 讨论(0)
  • 2020-11-28 21:56

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

    Using: -

    if fileUrl.checkFileExist()
       {
          // Do Something
       }
    
    0 讨论(0)
  • 2020-11-28 21:57

    Swift 4 example:

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

    I put the check in my loadData function which I called in viewDidLoad.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        loadData()
    }
    

    Then I defined loadData below.

    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...")
        }
    }
    
    0 讨论(0)
  • 2020-11-28 21:58

    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.

    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.

    0 讨论(0)
提交回复
热议问题