Lou
Lou

Reputation: 1163

Reading Contents of File Not Working with FileManager

I am new to Swift.

I am trying to write a simple app that just reads a file and converts its contents to a string. I am using FileManager and the example given here for Swift 4: Read and write a String from text file

It's not working though. The issue, I am assuming, is that I am giving the wrong URL to the String(contentsOf: URL) method. The exact error thrown is that it couldn't open the file because it doesn't exist.

Below is my ViewController.swift code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var testText: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let test = directoryContents()
        do {
            let text = try String(contentsOf: test)
            testText.text! = text
        }
        catch{
            print(error.localizedDescription)
        }
    }
}

func directoryContents() -> URL {
    var dirContents: URL!
    dirContents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    dirContents = dirContents.appendingPathComponent("testdata.txt")
    return dirContents
}

The rest of the app files are generic Single View App files. I would include an image of the sidebar, but the question editor was throwing an error when I tried to upload it. Basically, it looks like:

testingData/
 testingData/
  TestData/
   testdata.txt
  AppDelegate.swift
  ViewController.swfit
  Main.storyboard
  Assets.xcassets
  LaunchScreen.storyboard
  Info.plist
 Products/
  testingData.app

The Main.storyboard has a TextView added to it that is the testText in my ViewController. The file I am trying to read in is the testdata.txt, which is a text file containing the text 1,2,3,4,5,6 and nothing else. It is a member of the testingData app.

I'm not sure what I'm missing. If this is answered somewhere else on here, kindly point me in that direction and I'll close this out.

Upvotes: 1

Views: 727

Answers (1)

vadian
vadian

Reputation: 285082

If the file is in the application bundle you have to use the API of Bundle

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let test = Bundle.main.url(forResource:"testdata", withExtension: "txt")!
    do {
        let text = try String(contentsOf: test)
        testText.text! = text
    }
    catch {
        print(error)
    }
}

and delete directoryContents()

Upvotes: 4

Related Questions