I am working to get the contents of an NSData instance written to a file. I am currently using an Xcode playground.
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
}
}
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.
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/folders/bc/lgy7c6tj6pjb6cx0p108v7cc0000gp/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-105DE0AC-D5EF-46C7-B4F7-B33D8648FD50/newdata.json.