iosswiftdocumentsdirectory

How to read string from Text which saved in Documents Directory with Swift?


I have a Test.txt file saved in Documents Directory of an app. There are several names saved one by one in each line in the Test.txt file, like this:

Tom
Jack
Jerry
Jennifer
Lynn

I would like to add these names to an array, like this:

var nameList = ["Tom", "Jack", "Jerry", "Jennifer", "Lynn"]

Is there any way to get it work?

I have the following codes, but it will consider the names as one string.

  if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let archiveURL = dir.appendingPathComponent("Test").appendingPathExtension("txt")

            do {

                try Data(textView.text.utf8).write(to: archiveURL)
            }

            catch {
                print("error")
            }

            do {
                namesPool = try! [String(contentsOf: archiveURL, encoding: .utf8)]
            }

        }

The above codes will get the following array:

var nameList = ["Tom\nJack\nJerry\nJennifer\nLynn\n"]

Any suggestions would be appreciated.


Solution

  • You are missing one last step, separate it using:

    let namesTogether = try! String(contentsOf: archiveURL, encoding: .utf8)
    namesPool = namesTogether.components(separatedBy: "\n")