尝试将我们的Web服务读入UITableViewController,并且它仅将第一条记录返回给模拟器。希望有人能够看一下代码并指导我正确的方法。最终目标是将其放入UITableViewCell中,以便我可以很好地格式化,但只是希望获取所有记录。
这是将返回的部分json文件的视图。
{
"Count":11518,
"Result":[
{
"cuName": "#1",
"charter_Num":
"16328","City":
"Jonesboro",
"State_id": "GA",
"cuName_location": "#1 - Jonesboro, GA"
},
{
"cuName": "@lantec Financial",
"charter_Num": "7965",
"City": "Virginia Beach",
"State_id": "VA",
"cuName_location": "@lantec Financial - Virginia Beach, VA"
}]
}
这是在json网络服务中读取并尝试解析并放入表中的代码。
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
//Commented out the following lines because it doesn't return anything when using the modified code that works
//
// guard let data_list = json as? NSArray else
// {
// return
// }
//This code works but only gives me the 1st record back
if let cu_list = try? json as? [String:Any],
let result = cu_list?["Result"] as? [[String:Any]],
let charter_num = result[0]["charter_Num"] as? String,
let value = result[0]["cuName_location"] as? String, result.count > 0 {
TableData.append(value + " (" + charter_num + ")")
} else {
print("bad json - do some recovery")
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
最佳答案
您从result
对象引用第0个索引元素,它将仅从JSON数据返回第一个记录。您需要遍历循环,然后将数据追加到数组中,以便在UITableView
中填充数据。