Reading from a file swift 2

I'm trying to read a file which exist with the below code in Swift 2. It seems to be failing. Appreciate any inputs:


let someText = NSString(string:"some text")

let destinationPath = "/users/johnt/myFile.txt"

var filemgr = NSFileManager.defaultManager()

if filemgr.fileExistsAtPath(destinationPath) {

print("File exists")

do {

let readFile = try String(contentsOfFile: destinationPath, encoding: NSUTF8StringEncoding) // Throws this error

// How do I read the file contents from here?

print("\(readFile)")

} catch let error as NSError {

print("Error: \(error.domain)")

}

} else {

print("File does not exist")

do {

try someText.writeToFile(destinationPath, atomically: true, encoding: NSUTF8StringEncoding)

} catch let error as NSError {

print("Error: \(error.domain)")

}

}

I assume you tested your code in the Playground, as your code has no faults in syntax.

(You'd better describe your environment and the details of the error. Something requiring too much guess would be avoided.)


Playground is sandboxed, so, you cannot read or write arbitrary files in your system from within the Playground.


If you just want to write a code which reads some resource in the Playground, start with adding the resource to the Playground.

Adding Resources to a Playground


If you want to test a code which reads or writes arbitrary files, you'd better create a Command Line Tool project.

Accepted Answer

I suspect you are running into sandbox issues. I changed the code to print \(error) instead of \(error.domain) and am seeing "You don't have permission" errors when run in a playground. When I removed the hard path the code works. The file winds up in a path that looks something like ~/Library/Containers/com.apple.dt.playground.stub.OSX.OS-X-Play-7A27EB87-6E09-4A45-92DC-0FF0A4392AC4/Data/ where OS-X-Play is the name of my playground.


To answer your question the contents of the file are in the string "readFile".


let someText = NSString(string:"some text")
let destinationPath = "myFile.txt"
var filemgr = NSFileManager.defaultManager()
if filemgr.fileExistsAtPath(destinationPath) {
    print("File exists")
    do {
        let readFile = try String(contentsOfFile: destinationPath, encoding: NSUTF8StringEncoding)
        print("\(readFile)")
        // the above prints "some text"
    } catch let error as NSError {
            print("Error: \(error)")
    }
} else {
    print("File does not exist")
    do {
        try someText.writeToFile(destinationPath, atomically: true, encoding: NSUTF8StringEncoding)
    } catch let error as NSError {
        print("Error: \(error)")
    }
}

Thanks. Yes, I think the path was incorrect for some reason. In general, if I have a text file for my app which has app configurations, (a non-playground based), would I use a flat file, parse them out, or is there any other way to load the configurations into my app. I've to check out the resources maybe?

When you want use a readonly file-based resource, you just add the file into your app target, and Xcode will put it into the application bundle.

You can access such bundle resources like this:

let myFileURL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "txt")!
let myText = try! String(contentsOfURL: myFileURL, encoding: NSUTF8StringEncoding)
print(myText)

Structured files like plist or json can be easily parsed, as you like it.

Reading from a file swift 2
 
 
Q