[英]SWIFT Data in Table View not showing
我需要有關如何解決此問題的幫助。
我試圖使用json來獲取數據,但是當我嘗試在Table View中查看時,它沒有顯示。
我使用下面的代碼測試表視圖是否正常工作!
// self.clientList = [“芒果”,“香蕉”,“橙色”,“番石榴”,“葡萄”]
我使用下面的代碼測試json是否返回了數據。 仍然有效。
for item in jsonClientList {
let firstName = item["firstName"]
//Printing is working
print(firstName as! String)
}
線不工作! 我不知道為什么。 它在循環內部,但在加載表視圖時才對數據進行循環。
提前致謝。
self.clientList.append(firstName as!String)
//---------------------------------
var clientList:[String] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.clientList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "tblClientList")
cell.textLabel?.text = self.clientList[indexPath.row]
return cell
}
internal func jsonParser() -> Void{
//-------------------------
let postEndpoint: String = "http://domain.com/client"
let url = NSURL(string: postEndpoint)
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url!, completionHandler:
{
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
do{
let ipString = NSString(data:data!, encoding: NSUTF8StringEncoding)
if (ipString != nil) {
let jsonClientList = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
for item in jsonClientList {
let firstName = item["firstName"]
//I tried to print the data from json and its working!
print(firstName as! String)
//Line not working
//I tried to insert the firstName to clientList array
self.clientList.append(firstName as! String)
}
}
//If I use this its working
// self.clientList = ["Mango", "Banana", "Orange", "Guava", "Grapes"]
}
} catch{
print("Something bad happed!")
}
}
).resume()
//--------------
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
jsonParser()
}
//---------------------------------
您忘記刷新新數據以顯示在表格中,就像
self.clientList.append(firstName as! String)
}
dispatch_async(dispatch_get_main_queue())
self.yourtableViewname.reloadData()
}
如另一個答案中所述,問題是表視圖需要重新加載。
在Swift中,有一種更方便的方法來填充數據源數組,而無需使用map
函數進行重復循環。
像問題中一樣,它假設jsonClientList
中的所有字典jsonClientList
包含一個鍵firstName
。
tableView
是UITableView
實例的名稱。
...
let jsonClientList = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [[String:AnyObject]]
self.clientList = jsonClientList.map{ $0["firstName"] as! String }
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
} catch {
...
在這種情況下,不需要使用可變容器讀取JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.