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

前端 未结 12 2123
梦毁少年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: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         
        } else {
            print("The file DOES NOT exist! Mournful trumpets sound...")
        }
    }
    

提交回复
热议问题