简体   繁体   English

如何解决此“致命错误:在解开可选值时意外发现 nil”?

[英]How can I fix this "Fatal Error: unexpectedly found nil while unwrapping optional value"?

I have been working on my first iOS Swift project, and I am running into difficulty with a fatal error.我一直在从事我的第一个 iOS Swift 项目,但遇到了致命错误的困难。 This error reports unexpectedly found nil while unwrapping optional value only when getting an error message from the API being called.只有在从被调用的 API 获取错误消息时,此错误才会在解包可选值时报告意外发现 nil。

Here is the Swift code这是斯威夫特代码

@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


}

Here is the JSON result returned with an error这是返回错误的 JSON 结果

JSONDictionary {
"error_code" = "item_not_found";
"error_message" = "Item ID or UPC was invalid";
"status_code" = 404;
}

Here is the JSON result if the item is found by the API如果 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",
}

Since your dictionary structure changes and you are not sure on few keys being present, you must do a safe check before using them like this:由于您的字典结构发生了变化并且您不确定是否存在几个键,因此您必须在使用它们之前进行安全检查,如下所示:

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.

相关问题 为什么会出现以下错误:“致命错误:在展开可选值时意外发现nil”? -以及如何具体修复? - Why do I get the following error: “fatal error: unexpectedly found nil while unwrapping an Optional value”? - and how can I fix it specifically? 如何修复线程 1:致命错误:在隐式展开可选值时意外发现 nil? - How to fix Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value? 如何解决“致命错误:解开可选值时意外发现为零”出口按钮 - How to fix “ fatal error: unexpectedly found nil while unwrapping an Optional value ” outlet button 如何解决:“致命错误:在展开可选值(lldb)时意外发现nil” - How to fix: “fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)” ARQuicklook-致命错误:展开一个可选值时意外发现nil - ARQuicklook - Fatal error: Unexpectedly found nil while unwrapping an Optional value 致命错误:在AVFoundation中解开Optional值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value in AVFoundation 致命错误:展开一个可选值NSURL时意外发现nil - Fatal Error: Unexpectedly found nil while unwrapping an Optional value NSURL 致命错误:在展开可选值时意外发现 nil:文件 - Fatal error: Unexpectedly found nil while unwrapping an Optional value: file 致命错误:解开可选值计算时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value Computation WebView:致命错误:展开可选值时意外发现nil - WebView: fatal error: unexpectedly found nil while unwrapping an Optional value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM