-1

I would like to read the content from one text file in swift the step I did is

  1. go to terminal and read/create a file
  2. go to Xcode, File -> add file to My Project and select the test_this file into project
  3. 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?

jacobcan118
  • 7,797
  • 12
  • 50
  • 95
  • You seem to be doing two different things -- 1) Reading a file at `/Users/test_this` (which, by the way, is a very unusual place to put a file 2) Adding a file to your app's bundle and trying to read it. Which do you want to do? Keep in mind that if the answer is #1, if you app is sandboxed, you don't have access to files unless a user selects them first. – jnpdx Oct 01 '22 at 21:55
  • I want to do 2 and I try to add the file into my project directory also. I still get Nil – jacobcan118 Oct 02 '22 at 01:02
  • You get a file in your bundle by doing something like `Bundle.main.path(forResource:ofType:)`, not by using an absolute path the file on your computer. – jnpdx Oct 02 '22 at 01:06

1 Answers1

-1

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.

  1. open Xcode and navigate to your project, ensure the left panel shows the folders/files of your project.
  2. open Finder and navigate to your test.txt file.
  3. 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.