Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to read local file using Swift?

Tags:

swift

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

like image 819
eivindml Avatar asked Sep 15 '14 10:09

eivindml


People also ask

How do I open the file manager in IOS Swift?

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.


2 Answers

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) 
like image 146
Atomix Avatar answered Sep 29 '22 03:09

Atomix


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

like image 25
Grimxn Avatar answered Sep 29 '22 03:09

Grimxn