Read and Write Text Into a File in Swift

In this blog post, you will learn how to read and write text into a file in Swift. You will first write a string value into a text file and then read the content of that text file to see if it contains the string you have written to it. So the code below includes four short examples and a complete example showcase with Xcode playground:

  • Declare file name and file path.
  • Access the document directory.
  • Write text into a file.
  • Read the content of a text file.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Step 1: Declare Filename and Filepath

Let’s begin by declaring a filename and initializing the file path variable.

The filename is the name of the file you want to create or access. The file path is the location where the file will be stored. In the code snippet below, the filePath variable is initialized as an empty string because it will later be assigned the actual file path once the document directory is determined.

import Foundation

let fileName = "myFileName.txt" // Your File Name
var filePath = "" // Your file path

Step 2: Access the Document Directory

Before writing into a file, you need to access the document directory on the device.

The document directory is a place where your app can store user-generated content or data that cannot otherwise be recreated by your app. It is also the best place to store data that needs to be backed up by iCloud.

let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)

if dirs.count > 0 {
   let dir = dirs[0] //documents directory
   filePath = dir.appending("/" + fileName)
   print("Local path = \(filePath)")
} else {
   print("Could not find local directory to store file")
}

In the code example above, to access the document directory, I use the NSSearchPathForDirectoriesInDomains function, which returns an array of strings that are the paths of the directories that match the given parameters.

The first parameter is the type of directory I want to find, which is the document directory. The second parameter is the domain or scope of the search, which is all domains in this case. The third parameter is a boolean value that indicates whether to expand the tilde character (~) in the paths or not, which is true in this case.

The function returns an array of strings, which I store in a constant variable called dirs. Then I check if the array is not empty, which means that at least one document directory was found. If so, I get the first element of the array, which is the path of the document directory, and store it in another constant variable called dir.

Step 3: Write Text into a File

Now, you can write text into the file. To do this, use the write(toFile:atomically:encoding:) method of the String class. This method writes the contents of the string to a file at the specified path.

let fileContentToWrite = "Text to be recorded into file"

do {
   // Write contents to file
   try fileContentToWrite.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8) // UTF-8 Encoding
}
catch let error as NSError {
   print("An error took place: \(error)")
}

The UTF-8 encoding is used in the write(toFile:atomically:encoding:) method because it is a standard that supports a wide range of characters, making it suitable for text files. For more details, you can check out the official Apple documentation.

Step 4: Read the Content of a File

After writing the content, you can read it back using the String(contentsOfFile:encoding:) initializer. This method creates a new string object from the contents of a file at a specified path.

do {
   // Read file content
   let contentFromFile = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue)
   print(contentFromFile)
}
catch let error as NSError {
   print("An error took place: \(error)")
}

Complete example

Here is a complete example of how to read and write a string into a text file in Swift using the above code examples combined together:

import Foundation

let fileName = "myFileName.txt"
var filePath = ""

// Find documents directory on device
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)

if dirs.count > 0 {
   let dir = dirs[0] //documents directory
   filePath = dir.appending("/" + fileName)
   print("Local path = \(filePath)")
} else {
   print("Could not find local directory to store file")
}

// Set the contents
let fileContentToWrite = "Text to be recorded into file"

do {
   // Write contents to file
   try fileContentToWrite.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8)
}
catch let error as NSError {
   print("An error took place: \(error)")
}

// Read file content
do {
   // Read file content
   let contentFromFile = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue)
   print(contentFromFile)
}
catch let error as NSError {
   print("An error took place: \(error)")
}

You can check the generated file by visiting the output directory locations shown below screenshot. The file path will be changed for you based on your macs username.

Read and Write String Into a Text File

Let’s break the code into steps as before:

  1. Declares the filename and initializes the file path variable. The filename is the name of the file you want to create or access, and the filepath is the location where the file will be stored.
  1. Accesses the document directory on the device. The document directory is a place where your app can store user-generated content or data that cannot otherwise be recreated by your app.
  1. Writes a string value into the file. The write(toFile:atomically:encoding:) method of the String class is used to write the contents of the string to a file at the specified path.
  1. Reads the content of the file. The String(contentsOfFile:encoding:) initializer is used to create a new string object from the contents of a file at a specified path.

Conclusion

I hope this tutorial was helpful to you.

To learn more about Swift and to find other code examples and tutorials, please check Swift Code Examples page.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *