michael michael - 1 year ago 145
Swift Question

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)


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?

pda pda
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download