I\'ve tried to build up a document-based Cocoa app and when I tried to parse JSON in readFromData: ofType: error:
method, I got an error: fatal error: unexpec
Then your funciton should be:
override func readFromData(data: NSData?, ofType typeName: String?, error outError: NSErrorPointer) -> Bool {
if let loadedDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: outError) as? NSDictionary {
return true
} else {
return false
}
}
Now this function:
ourError
should error occurFYI I happened to write a JSON handler, too.
Which includes NSJSONSerialization.JSONObjectWithData
.
If the data does not contain a valid JSON object, the JSONObjectWithData
function will return a nil, so you need to do a conditional unwrapping as follows:
if let dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: jsonError) as? NSDictionary {
println("Dictionary: \(dict)")
} else {
println("nil")
let resultString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Flawed JSON String: \(resultString)")
}
I hope it helps..... e
Most likely the problem is that you have data that isn't actually JSON, so the deserialisation will return nil, or the data is an array, and converting it to a dictionary will obviously crash.
You don't seem to understand some of the basics. What do you think AllowFragments is going to achieve? And why did you change error to nil? Do you understand what the error variable is there for? It's there to tell you what errors the JSON parser found. By setting the variable to nil, you prevent it from helping you.