Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a text file line by line in Swift?

I just started learning Swift. I have got my code to read from the text file, and the App displays the content of the entire text file. How can I display line by line and call upon that line multiple times?

TextFile.txt contains the following:

1. Banana  2. Apple 3. pear 4. strawberry 5. blueberry 6. blackcurrant 

The following is what currently have..

  if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){         var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)             if let content = (data){                 TextView.text = content     } 

If there is another way of doing this please let me know. It would be much appreciated.

like image 991
ScarletEnvy Avatar asked Aug 03 '15 02:08

ScarletEnvy


People also ask

How do I read a text file in Swift?

To read a Text File in Swift, we can prepare the file url and then use String initializer init(contentsOf: url) that returns file content as a string.


1 Answers

Swift 3.0

if let path = Bundle.main.path(forResource: "TextFile", ofType: "txt") {     do {         let data = try String(contentsOfFile: path, encoding: .utf8)         let myStrings = data.components(separatedBy: .newlines)         TextView.text = myStrings.joined(separator: ", ")     } catch {         print(error)     } } 

The variable myStrings should be each line of the data.

The code used is from: Reading file line by line in iOS SDK written in Obj-C and using NSString

Check edit history for previous versions of Swift.

like image 157
Caleb Avatar answered Sep 18 '22 19:09

Caleb