Try something like this approach, given that you have added the test.txt
file to your Xcode project.
struct ContentView: View {
@State var fileTxt = ""
var body: some View {
Text(fileTxt)
.onAppear {
if let theString = readLocalData() {
fileTxt = theString
print("---> fileTxt: \(fileTxt)")
}
}
}
func readLocalData() -> String? {
if let pathString = Bundle.main.path(forResource: "test", ofType: "txt") {
let url = URL(fileURLWithPath: pathString)
do {
return try String(contentsOf: url)
// alternative
// let data = try Data(contentsOf: url)
// return String(data: data, encoding: .utf8)
} catch {
print(error) // <-- here important
}
}
// vadian cleaner alternative
// if let url = Bundle.main.url(forResource: "test", withExtension: "txt") {
// do {
// return try String(contentsOf: url)
// } catch {
// print(error) // <-- here important
// }
// }
return nil
}
}
With the test.txt
file content:
Hello World
Note: to add the file test.txt
to your Xcode
project.
- open
Xcode
and navigate to your project, ensure the left panel shows the folders/files of your project.
- open
Finder
and navigate to your test.txt
file.
- drag and drop the
test.txt
file from Finder
into your Xcode project left panel.
After doing that, Build
then run
my code.
Alternatively, you can create a New File
in Xcode, using: right mouse click on the left panel showing the folders/files,
then select New File...
, scroll down then select, Empty
file. Give it a name test.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.