TableView不显示来自API调用的带有JSON数据的文本 [英] TableView not displaying text with JSON data from API call
本文介绍了TableView不显示来自API调用的带有JSON数据的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Alamofire
和SwiftyJson
连接到API.
I connected to API using Alamofire
and SwiftyJson
.
我得到了这个JSON返回:
I got this JSON return:
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c202",
"name": "Leonardo Dicaprio",
"email": "leonardo_dicaprio@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
这是我的ViewController代码:
This is my ViewController code:
import UIKit
import Alamofire
import SwiftyJSON
class ViewController:UIViewController {
@IBOutlet weak var tblJSON: UITableView!
var arrRes = [[String : AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
getRequest()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getRequest() {
Alamofire.request("http://api.androidhive.info/contacts").responseJSON { (responseData) -> Void in
if ((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String : AnyObject]]
}
if self.arrRes.count > 0 {
self.tblJSON.reloadData()
}
}
}
}
//MARK: tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrRes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["email"] as? String
return cell
}
}
我无法在UITableView
上显示结果.
谁能帮我?谢谢!
I have trouble displaying result on the UITableView
.
Can anyone help me? Thanks!
推荐答案
您需要像这样实现UITableViewDataSource
和UITableViewDelegate
class ViewController:UIViewController, UITableViewDataSource, UITableViewDelegate
,在viewDidLoad
中,您需要像这样将DataSource
和Delegate
分配给tableView
and in viewDidLoad
you need to assign DataSource
and Delegate
to your tableView like this
override func viewDidLoad() {
super.viewDidLoad()
tblJSON.dataSource = self
tblJSON.delegate = self
getRequest()
}
这篇关于TableView不显示来自API调用的带有JSON数据的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文