I'm trying to learn the new Swift programming language. It looks great, but I'm having a difficult time doing something as simple as reading the content of a local .txt file.
I have tried the few examples I could find through Google, but they give compile errors, like this answer here: Read and write data from text file If I tweak the code a bit, it works, but can only read from a special location within the project.
Why isn't it just as simple to read a .txt file with Swift as it is with for instance Ruby? And how would I go about reading the content of a file located at ~/file.txt
?
Thnx
Do a print(path. absoluteString) and then $ open path in Terminal, to open the file or folder at path. Keep in mind that the directory (on your Mac) where a Simulator's files are stored can change between running your app.
If you have a tilde in your path you can try this:
let location = "~/file.txt".stringByExpandingTildeInPath let fileContent = NSString(contentsOfFile: location, encoding: NSUTF8StringEncoding, error: nil)
otherwise just use this:
let location = "/Users/you/Desktop/test.txt" let fileContent = NSString(contentsOfFile: location, encoding: NSUTF8StringEncoding, error: nil)
This gives you a string representation of the file, which I assumed is what you want. You can use NSData(contentsOfFile: location)
to get a binary representation, but you would normally do that for, say, music files and not a text file.
Update: With Xcode 7 and Swift 2 this doesn't work anymore. You can now use
let location = NSString(string:"~/file.txt").stringByExpandingTildeInPath let fileContent = try? NSString(contentsOfFile: location, encoding: NSUTF8StringEncoding)
This would work:
let path = "~/file.txt" let expandedPath = path.stringByExpandingTildeInPath let data: NSData? = NSData(contentsOfFile: expandedPath) if let fileData = data { let content = NSString(data: fileData, encoding:NSUTF8StringEncoding) as String }
Note that data
may be nil, so you should check for that.
EDIT: Don't forget conditional unwrapping - looks much nicer ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With