Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text file in Swift

Tags:

text

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?

like image 826
michael Avatar asked Oct 23 '25 16:10

michael


1 Answers

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.

like image 130
pda Avatar answered Oct 26 '25 06:10

pda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!