The problem is when there is incomplete data NSJSONSerialization.JSONObjectWithData
is crashing the application giving unexpectedly found nil while unwrappin
Updated for Swift 3
let jsonData = Data()
do {
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options:JSONSerialization.ReadingOptions(rawValue: 0))
guard let dictionary = jsonObject as? Dictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSON Dictionary! \(dictionary)")
}
catch let error as NSError {
print("Found an error - \(error)")
}
Swift 2
let JSONData = NSData()
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(JSONData, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSONDictionary! \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
}