Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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:.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...