0

i have one table view with two labels. I need to display the data which are coming from json. But now its not showing any data in table view:

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
    }
}

Any thing i missed,please help me out.

I am not able to see any data in my table view...

2

1 Answer 1

2

your code is partially correct, I followed your question

Step-1

Right click on the info.plist file, select open as, Source code. Add the lines of code that allow the http connection to this server.

enter image description here

do like

Step-2

For Server request

sendAsynchronousRequest is deprecated in this place use

 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()


}

For local Request

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()

}

Update and Edit

  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!
}

}

you can get the output like

enter image description here

For sample Project

Sign up to request clarification or add additional context in comments.

7 Comments

ok, can you please modify this code to print the json data in this api link. So that i can understand the flow of it !!
@user5513630 -- sure bro.
@Anbu.Karthick yes its worked well. but when i run my table view , for first time its not showing any thing, i need to pull down lable view( like refresh), then only its showing data ? why??? i get error This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
i have searched in so, dispatch_async(dispatch_get_main_queue(), { // code here }) this code where i have to insert to rectify my problem
give the some time to load bro, why you do like the full option , no need
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.