I have a simple program, meant to write a short string to a file on the Desktop. It consists of the following code:
let path: String = "~/Desktop/test.txt"
let text: String = "This works!"
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let filePath = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(path)
do {
try text.writeToURL(filePath, atomically: false, encoding: NSUTF8StringEncoding)
} catch let error {
print(error)
}
do {
let text2 = try NSString(contentsOfURL: filePath, encoding: NSUTF8StringEncoding)
}
}
However, this gives me the following error message:
Error Domain=NSCocoaErrorDomain Code=4 "The file “test.txt” doesn’t exist." UserInfo={NSFilePath=/var/folders/ff/6r67smy97bz1v7cfh1rsj6300000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.FileWriter-5BAB65C9-B88C-440B-BA44-3F904B3D01AA/Documents/~/Desktop/test.txt, NSUnderlyingError=0x7fc9eae09380 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Even though I already have a file called test.txt
in my Desktop. Any suggestions?