I would like to read the content from one text file in swift the step I did is
- go to terminal and read/create a file
- go to Xcode, File -> add file to My Project and select the test_this file into project
- use the following code to read the content.
/// terminal
/// $echo "some content" > /Users/test_this
/// swift
let file = "/Users/test_this"
let path = URL(fileURLWithPath: file)
let text = try? String(contentsOf: path)
however, after print out file, path and text. text is Nil. file and path looks fine how do I read the content from a text file in swift?
Try something like this approach, given that you have added the
test.txtfile to your Xcode project.With the
test.txtfile content:Note: to add the file
test.txtto yourXcodeproject.Xcodeand navigate to your project, ensure the left panel shows the folders/files of your project.Finderand navigate to yourtest.txtfile.test.txtfile fromFinderinto your Xcode project left panel.After doing that,
Buildthenrunmy code.Alternatively, you can create a
New Filein Xcode, using: right mouse click on the left panel showing the folders/files, then selectNew File..., scroll down then select,Emptyfile. Give it a nametest.txt. And the file will be created and added to your Xcode project. Open this file in Xcode and type this:Hello from the test.txt file. Build then run my code.