Search code examples
swifttext

Read text file in Swift


I am trying to read a text file from the program, which is

 var name = String.stringWithContentsOfFile("test.txt", encoding: NSUTF8StringEncoding, error:nil)

(where text.txt is under project folder)

I also tried:

 var name = String.stringWithContentsOfFile("/Users/Michael/Desktop/test.txt", encoding: NSUTF8StringEncoding, error:nil)

(Directory)

And both of them return a nil value to me. I checked the file and make sure it is a txt file with UTF-8 code. Can someone help me?


Solution

  • You have that problem, because you've specified the path to the file as a string, while it should be a path object. Try the following example:

    let path = NSBundle.mainBundle().pathForResource("fileName", ofType: "txt")
    var data = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)
    

    This example assumes that the file in question is located in your app bundle.