无法在Swift中写入文件,程序“找不到目录”。

时间:2016-07-03 16:22:47

标签: swift macos file nsurl file-writing

我有一个简单的程序,意味着将一个短字符串写入桌面上的文件。它由以下代码组成:

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

但是,这会给我以下错误消息:

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

即使我的桌面上已经有一个名为test.txt的文件。有什么建议吗?

0 个答案:

没有答案