Reading from Txt File in Swift 3

How do you read data from a text file in Swift 3 (XCode 8)

The main issue is that you cannot load rich text (RTF) formatted text into String. The Cocoa equivalent to RTF is NSAttributedString.

Load the RTF as Data, create an NSAttributedString and get the plain text with the string property.

var arrayClients = [[String:String]]() // do not use NSMutableArray in Swift
var dictClients = [String:String]()

if let url = Bundle.main.url(forResource:"data", withExtension: "rtf") {
do {
let data = try Data(contentsOf:url)
let attibutedString = try NSAttributedString(data: data, documentAttributes: nil)
let fullText = attibutedString.string
let readings = fullText.components(separatedBy: CharacterSet.newlines)
for line in readings { // do not use ugly C-style loops in Swift
let clientData = line.components(separatedBy: "\t")
dictClients["FirstName"] = "\(clientData)"
arrayClients.append(dictClients)
}
} catch {
print(error)
}
}

However for that kind of data structure RTF is not appropriate. Better use JSON or property list.

Read and write a String from text file

For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

Swift 3.x - 5.x

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

let fileURL = dir.appendingPathComponent(file)

//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}

//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}

Swift 2.2

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}

//reading
do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}

Swift 1.x

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file);
let text = "some text"

//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

Passing text from text file to UITextView in Swift 3

This is probably the simplest way of doing it.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textView: UITextView!

@IBAction func readFile1(_ sender: Any) {

self.textView.text = load(file: "file1")
}

@IBAction func readFile2(_ sender: Any) {

self.textView.text = load(file: "file2")
}

@IBAction func readFile3(_ sender: Any) {

self.textView.text = load(file: "file3")
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

self.textView.text = load(file: "file1")
}

func load(file name:String) -> String {

if let path = Bundle.main.path(forResource: name, ofType: "txt") {

if let contents = try? String(contentsOfFile: path) {

return contents

} else {

print("Error! - This file doesn't contain any text.")
}

} else {

print("Error! - This file doesn't exist.")
}

return ""
}
}

Read text file in Swift

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.

IOS Swift read text file on server

In Swift 3 it's current. But you are mixing up Swift 2 and 3 code anyway.

Please use modern API

let url = URL(string:"http://www.1111.com/1.txt")!
let task = URLSession.shared.dataTask(with:url) { (data, response, error) in
if error != nil {
print(error!)
}
else {
if let textFile = String(data: data!, encoding: .utf8) {
print(textFile)
}
}
}
task.resume()

Append data to txt file in Swift 3

You can use a FileHandle for appending the existing file after checking if the file already exists.

let titleString = "Line, Item 1, Item 2, Item 3"
var dataString: String
let list1 = [1, 2, 3, 4, 5]
let list2 = ["a", "b", "c", "d", "e"]
let list3 = ["p", "q", "r", "s", "t"]

do {
try "\(titleString)\n".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print(error)
}

for i in 0...4 {
dataString = String(list1[i]) + ": " + list2[i] + list3[i] + "\n"
//Check if file exists
do {
let fileHandle = try FileHandle(forWritingTo: fileURL)
fileHandle.seekToEndOfFile()
fileHandle.write(dataString.data(using: .utf8)!)
fileHandle.closeFile()
} catch {
print("Error writing to file \(error)")
}
print(dataString)
print("Saving data in: \(fileURL.path)")
}

Output:

Line, Item 1, Item 2, Item 3
1: ap
2: bq
3: cr
4: ds
5: et


Related Topics



Leave a reply



Submit