How to Check if a File Exists in the Documents Directory in Swift

28 February 2025 Stephan Petzl Leave a comment Xcode

When developing iOS applications, a common requirement is to verify the existence of a file in the Documents directory. This is particularly useful when you need to load a saved file each time the app launches, ensuring that the app handles the presence or absence of the file gracefully.

Checking File Existence in Swift

Below is a step-by-step guide on how to check if a file exists in the Documents directory using Swift. This example is applicable to Swift 4.x and newer versions.

Swift 5 Example


  do {
      let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
      let fileUrl = documentDirectory.appendingPathComponent("userInfo").appendingPathExtension("sqlite3")
      if FileManager.default.fileExists(atPath: fileUrl.path) {
          print("FILE AVAILABLE")
      } else {
          print("FILE NOT AVAILABLE")
      }
  } catch {
      print(error)
  }
  

In this code snippet:

  • We use FileManager.default.url(for:in:appropriateFor:create:) to get the URL for the Documents directory.
  • We append the file name and extension to this URL using appendingPathComponent and appendingPathExtension.
  • We then check the existence of the file using FileManager.default.fileExists(atPath:).

Additional Considerations

While the above method is straightforward, consider the following when implementing file existence checks:

  • Ensure that the file path is constructed correctly to avoid false negatives.
  • Handle exceptions and errors gracefully, providing fallback options or default values where necessary.

Enhancing Test Automation with Repeato

When developing mobile applications, automated testing is crucial for ensuring quality and reliability. Tools like Repeato can significantly streamline this process. Repeato is a no-code test automation tool that supports iOS, Android, and web apps.

With Repeato, you can efficiently create, run, and maintain automated tests without writing extensive code. Its computer vision and AI capabilities allow for fast test recording and execution. Additionally, Repeato supports data-driven and keyword-driven testing, making it a versatile tool for developers and QA teams looking to enhance their testing workflows.

Like this article? there’s more where that came from!