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. Commented Oct 19, 2017 at 12:50
  • @Y.Bonafons Thanks for all the input, sir. I get it work with Ayman’s help. 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")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for all the input, sir.
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 Comments

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?
rather than reading the file from the bundle, read it from the the download directory path.
Thanks a lot,really appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.