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 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)")
}
}