Reading a text file in Swift

I am trying to read a text file from a program that

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

      

(where text.txt is in your project folder)

I've also tried:

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

      

(Catalog)

And both of them return zero to me. I checked the file and made sure it is a txt file with UTF-8 code. Can anyone help me?

+3


source to share


1 answer


You have this problem because you specified the file path 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 specified file is in your application.

+5


source







All Articles