Ios 我怎样才能解决这个问题;致命错误:在展开可选值“0”时意外发现零;?
我一直在做我的第一个iOS Swift项目,我遇到了一个致命的错误。此错误报告仅当从调用的API获取错误消息时,在展开可选值时意外发现nil 这是Swift代码Ios 我怎样才能解决这个问题;致命错误:在展开可选值“0”时意外发现零;?,ios,json,swift,Ios,Json,Swift,我一直在做我的第一个iOS Swift项目,我遇到了一个致命的错误。此错误报告仅当从调用的API获取错误消息时,在展开可选值时意外发现nil 这是Swift代码 @IBAction func pressScan(sender: AnyObject) { let barcode = lastCapturedCode print("Received following barcode: \(barcode)") let url = "https://api.nu
@IBAction func pressScan(sender: AnyObject) {
let barcode = lastCapturedCode
print("Received following barcode: \(barcode)")
let url = "https://api.nutritionix.com/v1_1/item?upc="
let urlWithUPC = url + barcode! + "&appId=[app ID goes here]&appKey=[app key goes here]"
print("API Query: "+urlWithUPC)
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlWithUPC)!) { data, response, error in
// Handle result
print("Checked the bar code")
// let JSONData = NSData()
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSONDictionary \(JSONDictionary)")
let foodScreenName = (JSONDictionary as NSDictionary)["item_name"] as! String
let foodBrandName = (JSONDictionary as NSDictionary)["brand_name"] as! String
let fullFoodName = foodBrandName + " " + foodScreenName
dispatch_async(dispatch_get_main_queue(),{
self.foodName.text = fullFoodName
});
}
catch let JSONError as NSError {
print("\(JSONError)")
}
}.resume
}
以下是返回的JSON结果,其中包含一个错误
JSONDictionary {
"error_code" = "item_not_found";
"error_message" = "Item ID or UPC was invalid";
"status_code" = 404;
}
如果API找到该项,则显示JSON结果
JSONDictionary {
"item_id": "51c3d78797c3e6d8d3b546cf",
"item_name": "Cola, Cherry",
"brand_id": "51db3801176fe9790a89ae0b",
"brand_name": "Coke",
"item_description": "Cherry",
"updated_at": "2013-07-09T00:00:46.000Z",
"nf_ingredient_statement": "Carbonated Water, High Fructose Corn Syrup and/or Sucrose, Caramel Color, Phosphoric Acid, Natural Flavors, Caffeine.",
"nf_calories": 100,
"nf_calories_from_fat": 0,
"nf_total_fat": 0,
"nf_saturated_fat": null,
"nf_cholesterol": null,
"nf_sodium": 25,
"nf_total_carbohydrate": 28,
"nf_dietary_fiber": null,
"nf_sugars": 28,
"nf_protein": 0,
"nf_vitamin_a_dv": 0,
"nf_vitamin_c_dv": 0,
"nf_calcium_dv": 0,
"nf_iron_dv": 0,
"nf_servings_per_container": 6,
"nf_serving_size_qty": 8,
"nf_serving_size_unit": "fl oz",
}
由于您的字典结构发生了变化,并且您不确定是否有几个键存在,因此您必须在使用它们之前进行安全检查,如下所示:
if let screenName = (JSONDictionary as NSDictionary)["item_name"] {
foodScreenName = screenName as! String
}
if let brandName = (JSONDictionary as NSDictionary)["brand_name"] {
foodBrandName = brandName as! String
}
在你的代码的哪一行“意外发现零”?修复它?永远不要使用
代码>再次出现(除了!=
)。将所有这些情况包装在if-lets或类似的构造中。错误响应也包含JSON,因此在尝试将JSON解析为已找到的项之前,应该检查响应statusCode==200。也是一个好主意吗?而不是在解析字段时,如果服务器没有发送它们,则会得到此断言,因为在出现错误的情况下,(JSONDictionary as NSDictionary)[“item_name”]as没有键!字符串
或(JSONDictionary作为NSDictionary)[“brand_name”]作为!字符串
。您首先需要检查它们是否存在。可能存在重复的