2014-11-06 88 views
3

我在加載表格視圖時在swift中解析json文件時遇到了麻煩。表視圖不加載與迅速

解析數據表現不錯。但是沒有數據顯示在表格視圖中。

這是代碼:

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    @IBOutlet weak var redditListTableView: UITableView! 

    var tableData = [] 

    @IBAction func cancel(sender: AnyObject) { 
     self.dismissViewControllerAnimated(false, completion: nil) 
     println("cancel") 
    } 
    @IBAction func done(sender: AnyObject) { 
     println("done") 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     searchJsonFile("blabla.json") 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     println(tableData.count) 
     return tableData.count 
    } 

    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 0 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell") 

     let rowData: NSString = self.tableData[indexPath.row] as NSString 
     cell.textLabel.text = rowData as String 

     return cell 
    } 

    func searchJsonFile(searchFile: String) { 

     let urlPath = "http://data.../\(searchFile)" 
     let url = NSURL(string: urlPath) 
     let session = NSURLSession.sharedSession() 
     let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in 
      println("Task completed") 
      if(error != nil) { 
       // If there is an error in the web request, print it to the console 
       println(error.localizedDescription) 
      } 
      var err: NSError? 

      var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary 

      if(err != nil) { 
       println("JSON Error \(err!.localizedDescription)") 
      } 
      var results = [String]() 

      if let results1 = jsonResult["data"] as? NSDictionary{ 
       for (key, value) in results1 { 
        if let eng = value["eng"] as? NSDictionary { 
         if let name = eng["name"] as? NSString{ 
          results.append(name) 
         } 
        } 
       } 
      } 

      //println(results) OK!!!! 

      dispatch_async(dispatch_get_main_queue(), { 
       self.tableData = results 
       self.redditListTableView.reloadData() 
      }) 

     }) 

     task.resume() 

    } 

} 

回答

1

您在返回從numberOfSectionsInTableView 0 - 所以你沒有顯示的數據。你想1節 -

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 
+0

哦!非常感謝。我昨天在這工作,並嘗試了很多解決方案......問題解決了!非常感謝。 – jilu 2014-11-06 12:48:40

1

如果你沒有那麼部分只是刪除此功能,或者評論

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 0 
    } 

否則返回1