read local text file content get Nil in swift

265 Views Asked by At

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?

1

There are 1 best solutions below

9
On

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.