Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 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 Reply

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:.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...