If you are using playground it will always return nil because playground is sandboxed. You can place your file inside the documents directory but it is located somewhere else at your computer and probably looks like something like the String below.
"/var/folders/f9/yrxcqv_10m57prx9lwts4qy80000gq/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-iOS-NSDate-85BEA777-C527-4A79-9B4E-53427CF98B7D/Documents/".
You can open this folder using your finder Main Menu > Go > Go To Folder... (command-shift-G) and paste that directory path there.
You can locate your playground documents folder using the code below:
let documentDirectoryPath = (NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL).path!
Just place your file there and then you can open it as a String:
let fileName = documentDirectoryPath.stringByAppendingPathComponent("test.txt")
var error:NSError?
if "This is a sample sentence.".writeToFile(fileName, atomically: true, encoding: NSUTF8StringEncoding, error: &error) {
println("file successfully saved") // "file successfully saved"
} else {
if let error = error {
println(error.description)
}
}
if let myLoadedString = String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding, error: &error) {
println(myLoadedString) // "This is a sample sentence."
} else {
if let error = error {
println(error.description)
}
}
errorparameter to get information about the problem?