ios - Swift 3.0 和网络服务
<p><p>尝试将我们的 Web 服务读入 UITableViewController,它只将第一条记录返回给模拟器。所以希望有人能够查看代码并引导我走上正确的道路。最终目标是将它放入 UITableViewCell 中,这样我就可以很好地格式化但只是想获取所有记录。 </p>
<p>这是将返回的部分 json 文件的 View 。</p>
<pre><code>{
"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"
}]
}
</code></pre>
<p>这是读取 json web 服务并尝试解析并放入表中的代码。</p>
<pre><code>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? ,
let result = cu_list?["Result"] as? [],
let charter_num = result["charter_Num"] as? String,
let value = result["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()})
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您指的是 <code>result</code> 对象中的第 0 个索引元素,它只会返回 JSON 数据中的第 1 条记录。您需要通过循环运行并将数据附加到您需要用于在 <code>UITableView</code> 中填充数据的数组。</p></p>
<p style="font-size: 20px;">关于ios - Swift 3.0 和网络服务,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/41552772/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/41552772/
</a>
</p>
页:
[1]