2016-05-26 57 views
0

我能夠用循環內部的JSON數據成功填充數組,並且我試圖用相同的信息填充TableView的單元格,但目前該列表沒有內容。獲取JSON數據以從數組中填充TableView

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    @IBOutlet weak var table: UITableView! 

    var headlines = [String]() 
    let baseURL = "http://api.nytimes.com/svc/topstories/v1/business.json?api-key=123456789" 



    override func viewDidLoad() { 
     getJSON() 
     super.viewDidLoad() 
     self.table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 
     self.table.dataSource = self 
     self.table.delegate = self 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    func getJSON() { 

     let url = NSURL(string: baseURL) 
     let request = NSURLRequest(URL: url!) 
     let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) 
     let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in 

      if error == nil { 
       let SwiftyJSON = JSON(data: data!) 
       let theTitle = SwiftyJSON["results"].arrayValue 

       for title in theTitle{ 

        let titles = title["title"].stringValue 
        self.headlines.insert(titles, atIndex: 0) 
        //print("- " + titles) 
       } 

       print(self.headlines) 

      } 

      else { 
       print("there was an error") 
      } 
     } 

     task.resume() 

    } 


    // From the UITAbleViewDataSource 
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return headlines.count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = self.table.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell 
     cell.textLabel!.text = self.headlines[indexPath.row] 
     return cell 
    } 

    // From the UITableViewDelegate 
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     print("You tapped on cell # \(indexPath.row)") 
    } 
} 

回答

0

任務是異步的,所以當你裝,你必須重新加載你的表

func getJSON() { 

    let url = NSURL(string: baseURL) 
    let request = NSURLRequest(URL: url!) 
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) 
    let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in 

     if error == nil { 
      let SwiftyJSON = JSON(data: data!) 
      let theTitle = SwiftyJSON["results"].arrayValue 

      for title in theTitle{ 

       let titles = title["title"].stringValue 
       self.headlines.insert(titles, atIndex: 0) 
       //print("- " + titles) 
      } 

      print(self.headlines) 
      self.table.reloadData() 
     } 

     else { 
      print("there was an error") 
     } 
    } 

    task.resume() 

} 
+0

感謝陣!我在一分鐘前與朋友想到了這一點,我很感激幫助! –