2

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?

Suleiman
  • 63
  • 3
  • print your filePath first and check it! – user3441734 Jul 03 '16 at 17:33
  • 2
    From the fileURLWithPath docs: *"The path that the NSURL object will represent. path should be a valid system path. If path begins with a tilde, it must first be expanded with `stringByExpandingTildeInPath`."* – jtbandes Jul 03 '16 at 17:38
  • 1
    Possible duplicate of [Simple way to read local file using Swift?](http://stackoverflow.com/questions/25846459/simple-way-to-read-local-file-using-swift) or [Tilde-based Paths in Objective-C](http://stackoverflow.com/questions/1675852/tilde-based-paths-in-objective-c/1675867#1675867) – Kametrixom Jul 03 '16 at 17:52

0 Answers0