2015-10-10 38 views
-1

我一直在研究我的第一個iOS Swift項目,並且遇到了一個致命錯誤。此錯誤報告意外地發現爲零,而僅在從被調用的API獲取錯誤消息時才展開可選值。我該如何解決這個「致命錯誤:在解包可選值時意外發現零」?

這裏是斯威夫特代碼

@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; 
} 

這裏是JSON返回結果,如果該項目是由API發現

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", 
} 
+0

「意外發現無」您的代碼行是什麼? – matt

+0

修復它?永遠不要再使用'!'(除了'!=')。將所有這些案例都包含在if-let或類似的結構中。 – HAS

+0

您的錯誤響應也包含JSON,因此您應該在嘗試將JSON解析爲找到的項目之前檢查該響應的statusCode == 200。也是一個好主意使用?代替 !當解析字段時,服務器不會發送它們。 –

回答

1

由於您的字典結構發生變化,並且您不確定是否有幾個鑰匙存在,您必須執行安全檢查在使用它們之前如下所示:

if let screenName = (JSONDictionary as NSDictionary)["item_name"] { 
    foodScreenName = screenName as! String 
} 

if let brandName = (JSONDictionary as NSDictionary)["brand_name"] { 
    foodBrandName = brandName as! String 
} 
相關問題