2017-06-22 41 views
-3

覆蓋FUNC viewDidLoad中(){ super.viewDidLoad()呼叫可以扔掉,但是沒有標明 「嘗試」 和錯誤沒有被處理

//get the values from sql/Json 
    let url = URL(string: "https://example.com/dropdownmenu/phpGet.php") 
    let data = Data(contentsOf: url! as URL) 
    var tmpValues = try! JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray 
    tmpValues = tmpValues.reversed() as NSArray 
    reloadInputViews() 

    for candidate in tmpValues { 
    if let cdict = candidate as? NSDictionary { 

      //fullName is the column name in sql/json 

      let names = cdict["fullName"] 
      self.values.append(names! as AnyObject) 

     } 
    } 

} 

enter image description here

回答

5
let optData = try? Data(contentsOf: url! as URL) 
guard let data = optData else { 
    return 
} 

數據( contentsOf:url!as URL)可以拋出異常,您需要嘗試呼叫。 通過使用let optData = try? ...如果拋出異常,您將擁有一個有效的Data對象或nil

+0

謝謝,您節省了我的時間。 – Mehul

+1

後衛let jsonResponce =試試? JSON(data:data)else { failure(「error」) return } – Mehul

相關問題