Having searched through the many (many!) swift playground questions to even craft this code, I\'m still struggling.
I\'ve placed a text file in the Re
I have seen this problem with .txt files created from .rtf files using TextEdit.
I loaded a text.txt file in the resources folder of my playground using similar code to you. The file contents was "hello there" and was made by converting an .rtf file to .txt by changing the extension.
let path = NSBundle.mainBundle().pathForResource("text", ofType: "txt")//or rtf for an rtf file
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)
The output was:
{\rtf1\ansi\ansicpg1252\cocoartf1343\cocoasubrtf140 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\f0\fs24 \cf0 hello there}
So the "hello there" is embedded. This is the problem with all the layout information in a .rtf file.
I went back to TextEdit and created a true .txt file. After opening a file - Format|Make Plain Text
Now this same code gave the console output "hello there".
You can try creating a class for opening and saving your files:
update: Xcode 10 • Swift 4.2
class File {
class func open(_ path: String, encoding: String.Encoding = .utf8) -> String? {
if FileManager.default.fileExists(atPath: path) {
do {
return try String(contentsOfFile: path, encoding: encoding)
} catch {
print(error)
return nil
}
}
return nil
}
class func save(_ path: String, _ content: String, encoding: String.Encoding = .utf8) -> Bool {
do {
try content.write(toFile: path, atomically: true, encoding: encoding)
return true
} catch {
print(error)
return false
}
}
}
usage: File.save
let stringToSave: String = "Your text"
let didSave = File.save("\(NSHomeDirectory())/Desktop/file.txt", stringToSave)
if didSave { print("file saved") } else { print("error saving file") }
usage: File.open
if let loadedData = File.open("\(NSHomeDirectory())/Desktop/file.txt") {
print(loadedData)
} else {
println("error reading file")
}
If you prefer working with URL
s (as I do and recommended by Apple):
Note that in Swift 4, the class URL
already exists.
class Url {
class func open(url: URL) -> String? {
do {
return try String(contentsOf: url, encoding: String.Encoding.utf8)
} catch {
print(error)
return nil
}
}
class func save(url: URL, fileContent: String) -> Bool {
do {
try fileContent.write(to: url, atomically: true, encoding: .utf8)
return true
} catch {
print(error)
return false
}
}
}