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.txt
file to your Xcode project.With the
test.txt
file content:Note: to add the file
test.txt
to yourXcode
project.Xcode
and navigate to your project, ensure the left panel shows the folders/files of your project.Finder
and navigate to yourtest.txt
file.test.txt
file fromFinder
into your Xcode project left panel.After doing that,
Build
thenrun
my code.Alternatively, you can create a
New File
in Xcode, using: right mouse click on the left panel showing the folders/files, then selectNew File...
, scroll down then select,Empty
file. 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.