在Swift中用NSDictionary JSON填充UITableView

我是新鲜的。我叫API,我得到的请求和数据的响应。但是,我不知道如何填充数据从NSDictionary到TableviewCell.Can任何人都可以帮助我。

代码在这里:

var responseData:NSString =NSString(data:data!,encoding:NSUTF8StringEncoding)! println("Response Data is "+responseData) var error: NSError? let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary println("NSDictionary JSON Is",jsonData) var error1: NSError? var dict: NSDictionary =["Book_name":" "] } } 

我的回应数据是:

 Response Data is {"ListOfBooks":[{"Book_name":"javascript_tutorial"}]} (NSDictionary JSON Is, [ListOfBooks: ({"Book_name" = "javascript_tutorial"; } )]) 

如何将文件名“javascript_tutorial”列入tableview?

 let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary if jsonData { // process jsonData var arrayofBOOKs: NSArray = jsonData["ListOfBooks"] as NSArray for elem: AnyObject in arrayofBOOKs { let name = elem["Book_name"] as String println("Book_name: \(name)") // here add the string to array items.addObject(name) } tableView.reloadData } else { // couldn't load JSON, look at error } 

以下是要遵循的步骤:

步骤1

打开ViewController.swift类,并在类声明下添加一个新的tableview实例variables

 @IBOutlet var tableView: UITableView! 

第2步

为了符合UITableViewDelegateUITableViewDataSource protocol只需在类声明中的UIViewController之后用冒号分隔它们即可

 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { override func viewDidLoad() { super.viewDidLoad() var items = NSMutableArray() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } 

第3步

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell cell.textLabel?.text = items[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("You selected cell #\(indexPath.row)!") }