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

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

提交回复
热议问题