覆盖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)
}
}
}
答案 0 :(得分:12)
let optData = try? Data(contentsOf: url! as URL)
guard let data = optData else {
return
}
数据(contentsOf:url!as URL)可以抛出异常,您需要尝试调用。 通过使用let optData = try? ...如果抛出异常,您将拥有有效的Data对象或nil