Where to place a .txt file and read from it in a IOS project

Felix Me picture Felix Me · Nov 29, 2014 · Viewed 24.2k times · Source

i want to put a .txt file in my Xcode Swift Iphone project. First, i simply drag&dropped it from my desktop to the Supporting Files Folder from the project. Isn't there a Folder like on Android "assets", so i can place my files anywhere i want?

The file in my example is called README.txt which has a bunch of lines and paragraphs.

Simple enough, now I want to print the content of the README.txt file to a view.

How do i do the read function and what path should I insert, if my file is in the project /SupportFiles/README.txt?

Thanks alot!

Answer

Mundi picture Mundi · Nov 29, 2014
if let path = Bundle.main.path(forResource: "README", ofType: "txt") {
  do {
    textView.text = try String(contentsOfFile: path, encoding: .utf8)
  } catch let error {
    // Handle error here
  }
}

Just drop the file anywhere into the project browser and make sure it is added to the right target.

Just to expand on the answer, you can also place them in a folder and use: + pathForResource:ofType:inDirectory:.