0

Here is what I want to archive:

I have a couple of names, let's say it 100 names. These names are listed in a text file or an excel file. I would like to add those names to an array, when I tap a button.

var namesPool: [String] = []

enter image description here

But I have no ideas how to get it work. Any suggestions would be appreciated.

2
  • 1
    There is many things to do: Add the file in your ressources, parse the file and put the result in an array 'nameArray', create UI with a button, add an action on this button to copy a name from your nameArray to your namePool... Please clarify your question.
    – Y.Bonafons
    Commented Oct 19, 2017 at 12:50
  • @Y.Bonafons Thanks for all the input, sir. I get it work with Ayman’s help.
    – Vincent
    Commented Oct 19, 2017 at 13:27

2 Answers 2

3

The first step is to read the text from your file. There is a good example on how to do this here: Read and write data from text file

The second step is to convert the output String to an array. Since every name is on one line, you can separate each value by the \n newline character.

let names = fileNames.components(separatedBy: "\n")
1
  • Thanks for all the input, sir.
    – Vincent
    Commented Oct 19, 2017 at 13:26
2

First : add the text file into the project.

Second: make sure it's present in Build Phases -> Copy Bundle Resources.

 func getNames(fileName: String) -> [String]?
 {
     guard let path = Bundle.main.path(forResource: fileName, ofType: "txt") else
     {
         return nil
     }

     do
     {
         let content = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
            return content.components(separatedBy: "\n")
     }
     catch _ as NSError
     {
         return nil
     }
 }

Usage:

let namesPool = getNames(fileName:"names")
3
  • Thanks, Ayman. That's what I need. But if I didn't have the text file in the project, I mean how can I add a text file when I tap a button, after the project was built as an app? Any ideas you can share with me?
    – Vincent
    Commented Oct 19, 2017 at 13:14
  • rather than reading the file from the bundle, read it from the the download directory path. Commented Oct 19, 2017 at 13:20
  • Thanks a lot,really appreciated.
    – Vincent
    Commented Oct 19, 2017 at 13:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.