如何在Swift中将NSData写入新文件?

我正在努力将NSData实例的内容写入文件。 我目前正在使用Xcode游乐场。

这是我的代码:

let validDictionary = [ "numericalValue": 1, "stringValue": "JSON", "arrayValue": [0, 1, 2, 3, 4, 5] ] let rawData: NSData! if NSJSONSerialization.isValidJSONObject(validDictionary) { do { rawData = try NSJSONSerialization.dataWithJSONObject(validDictionary, options: .PrettyPrinted) try rawData.writeToFile("newdata.json", options: .DataWritingAtomic) } catch { // Handle Error } } 

我有一个名为newdata.json的文件位于资源中,但是当我检查它时,里面什么都没有。 我也尝试删除并查看是否将创建该文件,但它仍然无效。

您的代码是正确的,但文件未写入您期望的位置。 Swift Playgrounds是沙箱,文件位于系统的另一部分,而不是项目的资源文件夹中。

您可以通过立即尝试从中读取来检查文件是否实际被保存,如下所示:

 let validDictionary = [ "numericalValue": 1, "stringValue": "JSON", "arrayValue": [0, 1, 2, 3, 4, 5] ] let rawData: NSData! if NSJSONSerialization.isValidJSONObject(validDictionary) { // True do { rawData = try NSJSONSerialization.dataWithJSONObject(validDictionary, options: .PrettyPrinted) try rawData.writeToFile("newdata.json", options: .DataWritingAtomic) var jsonData = NSData(contentsOfFile: "newdata.json") var jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: .MutableContainers) // -> ["stringValue": "JSON", "arrayValue": [0, 1, 2, 3, 4, 5], "numericalValue": 1] } catch { // Handle Error } } 

来自Tom的评论如下:具体来说,该文件位于某个地方,如/private/var/folder‌​s/bc/lgy7c6tj6pjb6cx0‌​p108v7cc0000gp/T/com.‌​apple.dt.Xcode.pg/con‌​tainers/com.apple.dt.‌​playground.stub.iOS_S‌​imulator.MyPlayground‌​-105DE0AC-D5EF-46C7-B‌​4F7-B33D8648FD50/newd‌​ata.json.

如果您使用Xcode 8,那么有一种更好的方法。

首先,在Documents文件夹中创建一个名为Shared Playground Data

接下来,在您的操场上导入游乐场支持:

 import PlaygroundSupport 

最后,在文件URL中使用playgroundSharedDataDirectory 。 它将指向上面创建的文件夹:

 let fileURL = playgroundSharedDataDirectory.appendingPathComponent("test.txt") 

然后,您可以在操场上读取/写入该URL,并且(更容易)检查您正在保存的文件。 这些文件将位于您在上面创建的Shared Playground Data文件夹中。

使用以下扩展名:

 extension Data { func write(withName name: String) -> URL { let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name) try! write(to: url, options: .atomicWrite) return url } }