user2039697 user2039697 - 3 months ago 9
JSON Question

How to prevent app from crashing in case JSON answer is empty?

I have a API call which sometimes returns empty because there are no data in the DB. In such a case, the app crashes with the following error message.

Could not cast value of type 'NSTaggedPointerString' (0x108156ae8) to 'NSArray' (0x108156b88).


How can I prevent the app from crashing in case the JSON object is empty?

This is the class:

restApi.getAllNonAcademicSchools(self.shareData.token_type, accessToken: self.shareData.access_token, countryISOcode: self.shareData.studyLocationISOcode) {responseObject, error in
// use responseObject and error here

//create custom session with auth header / token from REST API for getting images
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()

//Get the access token here and create HTTP header used for auth
let xHTTPAdditionalHeaders: [String : String] = ["Authorization" : self.shareData.token_type + " " + self.shareData.access_token]

sessionConfig.HTTPAdditionalHeaders = xHTTPAdditionalHeaders
self.imageDownloader = ImageDownloader(
configuration: sessionConfig,
downloadPrioritization: .LIFO,
maximumActiveDownloads: 4,
imageCache: AutoPurgingImageCache()
)
print("imageDownloader object created")
print("print the json data from api ")
self.items = NSDictionary(dictionary: responseObject! as! [NSObject : AnyObject])
self.tableView.reloadData()

//access the inner array from the json answer called result

self.resultList = self.items["result"] as! [[String:
AnyObject]] //This is the line which causes the error
print(self.resultList)


self.tableView!.reloadData() // reload tableview when result comes back from async call

}


If data is available in the DB, everything works fine.

If data is in the DB, the following JSON response is being returned and everything works fine:

(
{
address = "Modern Mansion, Xiangyang South Rd, Bldg. A, 9th Floor, Room 910, Shanghai";
city = Shanghai;
"cou_id" = CN;
environment = L;
image = "LTL_Mandarin_Shanghai_3.jpeg";
name = "LTL Mandarin School";
rating = 0;
"sco_id" = 26;
"sco_type" = LS;
},

Answer

You can use if let or guard for Optional wrapping instead of force wrapping for that.

Using if let

if let response = self.items["result"] as? [[String: AnyObject]] {
    self.resultList = response
}

Using guard

guard let response = self.items["result"] as? [[String: AnyObject]] else {
     return
}
self.resultList = response