xcode 如何在 Swift 中将 NSData 写入新文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38987043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write NSData to a new file in Swift?
提问by dozo
I am working to get the contents of an NSData instance written to a file. I am currently using an Xcode playground.
我正在努力将 NSData 实例的内容写入文件。我目前正在使用 Xcode 游乐场。
This is my code:
这是我的代码:
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
}
}
I have a file named newdata.json located in resources but when I check it there is nothing inside. I also tried deleting and seeing if the file will be created but it still doesn't work.
我有一个名为 newdata.json 的文件位于资源中,但是当我检查它时,里面什么也没有。我也尝试删除并查看是否会创建该文件,但它仍然不起作用。
采纳答案by Carter
Your code is correct, but the file is not being written where you expect. Swift Playgrounds are sandboxed and the files are in another part of the system, not in your project's resources folder.
您的代码是正确的,但文件没有写入您期望的位置。Swift Playgrounds 是沙盒的,文件位于系统的另一部分,而不是项目的资源文件夹中。
You can check that the file is actually being saved by immediately trying to read from it, like so:
您可以通过立即尝试读取文件来检查文件是否确实已保存,如下所示:
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
}
}
From Tom's comment below: Specifically, the file is in some place like /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.
来自 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.
回答by Bart?omiej Semańczyk
Use following extension:
使用以下扩展名:
extension Data {
func write(withName name: String) -> URL {
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name)
try! write(to: url, options: .atomicWrite)
return url
}
}
回答by Tom Harrington
If you are using Xcode 8, there's a better approach.
如果您使用的是 Xcode 8,则有更好的方法。
First, create a directory in your Documents
folder called Shared Playground Data
.
首先,在您的Documents
文件夹中创建一个名为Shared Playground Data
.
Next, import playground support in your playground:
接下来,在您的操场中导入操场支持:
import PlaygroundSupport
Finally, use playgroundSharedDataDirectory
in your file URLs. It will point to the folder created above:
最后,playgroundSharedDataDirectory
在您的文件 URL 中使用。它将指向上面创建的文件夹:
let fileURL = playgroundSharedDataDirectory.appendingPathComponent("test.txt")
You can then read/write that URL in your playground, and (more easily) inspect the files that you're saving. The files will be located in the Shared Playground Data
folder you created above.
然后,您可以在您的 Playground 中读/写该 URL,并(更轻松地)检查您正在保存的文件。这些文件将位于Shared Playground Data
您在上面创建的文件夹中。