Simple way to read local file using Swift?

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


    let file = "/Users/user/Documents/text.txt"
    let path=URL(fileURLWithPath: file)
    let text=try? String(contentsOf: path)

Tags:

Swift