July 25, 2020

Working with application directory in iOS swift

By Mohit Agrawal

Let’s see how to write a text file in the application directory of an iOS app

Introduction

In the previous tutorial, I have shown you how to use UserDefaults to store the user’s data. But it can store a very small amount of data like the user’s name or something like setting preferences.

Now the question is how to store some big files like 10MB or even more than that 🤔?

What is application document directory ?

Here comes the application directory, apple provides a directory to the app where you can do read and write in the device storage.

Each app has its own directory. It means no other app can access other app’s directory.

There is no limitation on file size we store in the app directory by the OS. This directory will be deleted automatically as soon as you delete the app.

What we will build?

In this iOS tutorial, I will show you how to create a text file and save it in the application directory of the app. After that, we will see how to read the data back from the same text file.

Implementation

How to create a text file in the application directory of your iOS app swift?

1 STEP: Create a new blank iOS project in swift language and name it “App Directory”.

2 STEP: Let’s create a basic UI. We need one text view so that the user can give an input string. Two buttons, one for creating a file and another for reading the file. Lastly, one text field to display the text after reading the file.

ios_application_directory_1

Open the Main.storyboard and create a UI like this. Your UI should not be exact because our main focus is on the logical part of writing and reading the file.

3 STEP: Now this is the step for which you were waiting. The coding part 🤩. I will create two methods.

  • func createFile(with name: String, data: String){}: This method will create a new file. It takes two parameters. The first parameter is the name of the file and the second parameter is the string data which has to be written in the file.
  • func readFileContent(from name: String, completion:(_ data: String) -> Void) {}: This method will read the file content and return the file data using a completion handler.

Open your viewcontroller.swift and copy paste this code.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var inputTextField: UITextField!
    @IBOutlet weak var outputTextView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    func createFile(name: String, data: String) {
        // find all possible documents directories for this user
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

        //Writing text file
        let path = paths[0].appendingPathComponent(name + ".txt")
        
        do {
            try data.write(to: path, atomically: true, encoding: String.Encoding.utf8)
        } catch {
            print("Error in writing: \(error)")
        }
        
    }
    
    func readFileContent(from name: String, completion:(_ data: String) -> Void) {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let path = paths[0].appendingPathComponent(name + ".txt")
        do {
            let text = try String(contentsOf: path, encoding: .utf8)
            self.outputTextView.text = text
        } catch {
            self.outputTextView.text = "File not found: \(error)"
        }
    }
    @IBAction func didTapCreateFile(_ sender: Any) {
        createFile(name: "myfile", data: inputTextField.text ?? "No input")
    }
    @IBAction func didTapReadFile(_ sender: Any) {
        readFileContent(from: "myfile") { (data) in
            outputTextView.text = data
        }
    }
}

paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return the paths for all possible documents directories for the user and paths[0] contains the document directory of the app.

4 STEP: I hope 🤞 , above code blocks are easy to understand. Now run the code and see the outcome.

If you have followed everything correctly till here then you should be able to get the expected outcome like this.

ios_application_directory_2

Please let me know in the comment section if you are getting any issues. I am here to help you out 🙏🏼.

Subscribe YouTube: More tutorials like this

I hope this blog post is useful for you, do let me know your opinion in the comment section below.
I will be happy to see your comments down below 👏.
Thanks for reading!!!

My gaming PC build:
🔥 Graphics card: https://amzn.to/3hdZjzc
🔥 RAM: https://amzn.to/30zIh7I
🔥 Gaming motherboard: https://amzn.to/30ANEE1
🔥 Cabinet: https://amzn.to/32Dibn1
🔥 SSD: https://amzn.to/32D4VyK
🔥 AMD processor: https://amzn.to/2OKP8FW
🔥 PSU: https://amzn.to/32HRJJ0
🔥 Gaming RGB keyboard: https://amzn.to/2CnVVmF
🔥 Gaming RGB Mouse: https://amzn.to/3jna4Rv