没有在表格视图swift中显示数据

时间:2016-03-19 10:55:09

标签: ios json swift

我有一个带有两个标签的表格视图。我需要显示来自json的数据。但现在它没有在表格视图中显示任何数据:

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
    let yourJsonFormat: String = "JSONFile" // set text JSONFile : json data from file
                                            // set text JSONUrl : json data from web url

    var arrDict :NSMutableArray=[]

    @IBOutlet weak var tvJSON: UITableView!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        if yourJsonFormat == "JSONFile" {
            jsonParsingFromFile()
        } else {
            jsonParsingFromURL()
        }
    }

    func jsonParsingFromURL () {
        let url = NSURL(string: "url")
        let request = NSURLRequest(URL: url!)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in

        }
    }

    func jsonParsingFromFile()
    {
        let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
        let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)


    }

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

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
        let strTitle : NSString=arrDict[indexPath.row] .valueForKey("name") as! NSString
        let strDescription : NSString=arrDict[indexPath.row] .valueForKey("rating") as! NSString
        cell.lblTitle.text=strTitle as String
        cell.lbDetails.text=strDescription as String
        return cell as TableViewCell
    }
}

我想念的任何事情,请帮助我。

我无法在表格视图中看到任何数据......

1 个答案:

答案 0 :(得分:2)

您的代码部分正确,我按照您的问题

<强>步骤1

  

右键单击info.plist文件,选择打开为源代码。添加允许http连接到此服务器的代码行。

enter image description here

喜欢

<强>步骤-2

对于服务器请求

sendAsynchronousRequest 在此处使用

已弃用
 func jsonParsingFromURL () {
    let url = NSURL(string: "url")
    let session = NSURLSession.sharedSession()

let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
  print("done, error: \(error)")
  let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary 
  arrDict.addObject((dict.valueForKey("xxxx") 
  tvJSON .reloadData()

}
dataTask.resume()


}

对于本地请求

func jsonParsingFromFile()
  {
    let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
    let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)
       let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary 
  arrDict.addObject((dict.valueForKey("xxxx") 
  tvJSON .reloadData()

}

更新和修改

  class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet var showtable: UITableView!
 var arrDict :NSMutableArray=[]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

     self.jsonParsingFromURL()
}

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

func jsonParsingFromURL () {
    let url = NSURL(string: "http://kirisoft.limitscale.com/GetVendor.php?category_id=1")
    let session = NSURLSession.sharedSession()

    let request = NSURLRequest(URL: url!)
    let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
        print("done, error: \(error)")
        if error == nil
        {
        self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray

        print(self.arrDict)

            if (self.arrDict.count>0)
            {

                self.showtable.reloadData()
            }

       // arrDict.addObject((dict.valueForKey("xxxx")
        }


    }
    dataTask.resume()


}

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

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let CellIdentifier: String = "cell"

    var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as UITableViewCell!

    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: CellIdentifier)
    }


    cell?.textLabel!.text=arrDict[indexPath.row] .valueForKey("name")   as? String
     cell?.detailTextLabel!.text=arrDict[indexPath.row] .valueForKey("rating")   as? String

    return cell!
}

}

你可以获得像

这样的输出

enter image description here

sample Project