[英]Why do I get the following error: “fatal error: unexpectedly found nil while unwrapping an Optional value”? - and how can I fix it specifically?
[英]How can I fix this "Fatal Error: unexpectedly found nil while unwrapping optional value"?
我一直在從事我的第一個 iOS Swift 項目,但遇到了致命錯誤的困難。 只有在從被調用的 API 獲取錯誤消息時,此錯誤才會在解包可選值時報告意外發現 nil。
這是斯威夫特代碼
@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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.