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

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

I use the [ .writeFilePath ] method to save the image in the Documents folder, and I want to load it every time the application is launched. But I have a default image if there is no saved image.

But I just can't figure out how to use the [ func fileExistsAtPath(_:) ] function. Can anyone give an example of using a function with a path argument passed to it.

I believe that I do not need to embed any code as this is a general question. Any help would be greatly appreciated.

Greetings

+108
ios xcode swift
Jun 12 '14 at 10:05
source share
11 answers

version of Swift 4.x

  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 version 3.x

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

version of Swift 2.x , you must 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") } 
+197
Mar 03 '16 at 14:36
source share

Check out the code below:

Swift 1.2

 let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let getImagePath = paths.stringByAppendingPathComponent("SavedFile.jpg") let checkValidation = NSFileManager.defaultManager() if (checkValidation.fileExistsAtPath(getImagePath)) { println("FILE AVAILABLE"); } else { println("FILE NOT AVAILABLE"); } 

Swift 2.0

 let paths = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) let getImagePath = paths.URLByAppendingPathComponent("SavedFile.jpg") let checkValidation = NSFileManager.defaultManager() if (checkValidation.fileExistsAtPath("\(getImagePath)")) { print("FILE AVAILABLE"); } else { print("FILE NOT AVAILABLE"); } 
+33
Jun 12 '14 at 10:17
source share

Currently (2016), Apple is recommending more and more to use APIs related to NSURL URLs, NSFileManager , etc.

To get the document catalog in iOS and Swift 2 use

 let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) 

try! safe in this case because this standard directory is guaranteed to exist.

Then add the appropriate path component, e.g. sqlite file

 let databaseURL = documentDirectoryURL.URLByAppendingPathComponent("MyDataBase.sqlite") 

Now check if the file exists with checkResourceIsReachableAndReturnError NSURL .

 let fileExists = databaseURL.checkResourceIsReachableAndReturnError(nil) 

If you need an error, pass an NSError pointer to the parameter.

 var error : NSError? let fileExists = databaseURL.checkResourceIsReachableAndReturnError(&error) if !fileExists { print(error) } 

Swift 3+:

 let documentDirectoryURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let databaseURL = documentDirectoryURL.appendingPathComponent("MyDataBase.sqlite") 

checkResourceIsReachable is marked as can throw

 do { let fileExists = try databaseURL.checkResourceIsReachable() // handle the boolean result } catch let error as NSError { print(error) } 

To consider only the logical return value and ignore the error, use the nil-coalescing operator

 let fileExists = (try? databaseURL.checkResourceIsReachable()) ?? false 
+24
Apr 27 '16 at 18:06
source share

It is quite user friendly. Just work with the SingleManager NSFileManager defaultManager syntax, and then use the fileExistsAtPath() method, which simply takes the string as an argument and returns 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 here!! } 

Note that in Swift 2 there is no descending line in String.

+15
Jun 12 '14 at 10:08
source share

Alternative / recommended code template in Swift 3 :

  • Use URL instead of FileManager
  • Using Exception Handling

     func verifyIfSqliteDBExists(){ let docsDir : URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let dbPath : URL = docsDir.appendingPathComponent("database.sqlite") do{ let sqliteExists : Bool = try dbPath.checkResourceIsReachable() print("An sqlite database exists at this path :: \(dbPath.path)") }catch{ print("SQLite NOT Found at :: \(strDBPath)") } } 
+5
Nov 04. '16 at 14:11
source share

For Beginners Swift 3 :

  • Swift 3 handled most of NextStep syntax
  • So NSURL, NSFilemanager, NSSearchPathForDirectoriesInDomain are no longer used
  • Use URL and FileManager instead
  • NSSearchPathForDirectoriesInDomain not required
  • Use FileManager.default.urls instead

Here is sample code to check if a file named "database.sqlite" exists in the 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)") } } 
+4
Nov 04. '16 at 13:27
source share

Very simple: If your path is an instance of the URL, it is converted to a string using the path method.

  let fileManager = FileManager.default var isDir: ObjCBool = false if fileManager.fileExists(atPath: yourURLPath.path, isDirectory: &isDir) { if isDir.boolValue { //it a Directory path }else{ //it a File path } } 
+2
Jun 19 '17 at 7:19
source share

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 a 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...") } } 
+1
Jul 13 '18 at 8:13
source share

You must add a "/" slash in front of the file name, or you will get the path as "... / DocumentsFilename.jpg"

0
Apr 05 '15 at 17:38
source share

This works great 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 this is useful to someone. @; -]

0
Jan 22 '19 at 0:57
source share

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

Via: -

 if fileUrl.checkFileExist() { // Do Something } 
0
Apr 20 '19 at 19:28
source share



All Articles