The problem is when there is incomplete data NSJSONSerialization.JSONObjectWithData
is crashing the application giving unexpectedly found nil while unwrappin
Swift 3 NSJSONSerialization sample (read json from file):
file data.json (example from here: http://json.org/example.html)
{
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID":"SGML",
"SortAs":"SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso":[
"GML",
"XML"
]
},
"GlossSee":"markup"
}
}
}
}
}
file JSONSerialization.swift
extension JSONSerialization {
enum Errors: Error {
case NotDictionary
case NotJSONFormat
}
public class func dictionary(data: Data, options opt: JSONSerialization.ReadingOptions) throws -> NSDictionary {
do {
let JSON = try JSONSerialization.jsonObject(with: data , options:opt)
if let JSONDictionary = JSON as? NSDictionary {
return JSONDictionary
}
throw Errors.NotDictionary
}
catch {
throw Errors.NotJSONFormat
}
}
}
func readJsonFromFile() {
if let path = Bundle.main.path(forResource: "data", ofType: "json") {
if let data = NSData(contentsOfFile: path) as? Data {
do {
let dict = try JSONSerialization.dictionary(data: data, options: .allowFragments)
print(dict)
} catch let error {
print("\(error)")
}
}
}
}