Read Text File in Swift

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)
}

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()

How to read a text file while developing an ios app using xcode

You can read a file easily in iOS. Follow these steps:

Step 1: Add a File into project

Sample Image

Step 2: Reading a file

EDIT

Swift:

    let filePath = Bundle.main.path(forResource: "File", ofType: "txt");
let URL = NSURL.fileURL(withPath: filePath!)

do {
let string = try String.init(contentsOf: URL)

// use string here
print("read: " + string)
} catch {
print(error);
}

Objective-C:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSURL *url = [NSURL fileURLWithPath: filePath];
NSString *string = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

Thanks!

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 a text file line by line in Swift?

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.

Swift file not found when trying to read text file

First check wether you have added target on your text file (coordinates.txt)

Make sure that your text file(coordinates.txt) added target membership.

Second

let filename = Bundle.main.path(forResource: "coordinates", ofType: "txt")
let contents = try! String(contentsOfFile: filename)
let lines = contents.split(separator:"\n")

for line in lines {
print("\(line)")
}

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 ""
}
}


Related Topics



Leave a reply



Submit