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

703 views Asked by At

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.

2

There are 2 answers

5
Milan Nosáľ On BEST ANSWER

You are missing one last step, separate it using:

let namesTogether = try! String(contentsOf: archiveURL, encoding: .utf8)
namesPool = namesTogether.components(separatedBy: "\n")
3
Tomasz Czyżak On

Swift 4

// String with multiple names separated by end of line
let nameStr = try! String(contentsOf: archiveURL, encoding: .utf8)
// array of Substrings
let nameArray = nameStr.split(separator: "\n") 
// first name as String
let name = String(nameArray[0])

More about handling strings:Strings Cheat Sheet