0

I have been trying to pick up data from a trading site, with the api: "https://bittrex.com/api/v1.1/public/getmarketsummaries" and need to take out some values from here. I need a guidance on understanding the JSONarray and Dictionary. Please, if the code can be improved as well.

import UIKit

class DemoJsonTableViewController: UITableViewController {

var listData = [[String : AnyObject]]()

override func viewDidLoad() {
    super.viewDidLoad()

    let url:String = "https://bittrex.com/api/v1.1/public/getmarketsummaries"

    let urlRequest = URL(string: url)

    URLSession.shared.dataTask(with: urlRequest!) { (data, response, error) in



        if(error != nil){
            print(error.debugDescription)
        }
        else{
            do{
                self.listData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
                {
                    self.listData = dictionary["result"] as! [[String:AnyObject]]
                }

                    self.tableView.reloadData()

            }catch let error as NSError{
                print(error)
            }
        }
    }.resume()
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

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

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return self.listData.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

   let item = self.listData[indexPath.row]
    cell.textLabel?.text = item["MarketName"] as? String
    print(self.listData.count)

    return cell
}


/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}
*/

/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // Delete the row from the data source
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}
*/

/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the item to be re-orderable.
    return true
}
*/

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

And this is the link from where I want to import "MarketName" and "Last" into a table view but can't understand the JSONarray, etc.

Please, help needed. Im very new to coding so It'll be kind enough if you could correct the code. Thanks

Lorenzo
  • 3,293
  • 4
  • 29
  • 56

1 Answers1

0

Add this to the top of your UITableViewController:

var listData = [[String : AnyObject]]()

And replace your URLSession code with:

URLSession.shared.dataTask(with: urlRequest!) { (data, response, error) in
  if(error != nil){
    print(error.debugDescription)
  }
  else{
    do{
      let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
      self.listData = response["result"] as! [[String:AnyObject]]
      DispatchQueue.main.async {
          self.tableView.reloadData()
      }
    }catch let error as NSError{
      print(error)
    }
  }
  }.resume()

I hope it helps you.

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
  • @SiddhantMehandru please accept and upvote answer if this is correct and works for you. – Pranav Kasetti Sep 09 '17 at 15:24
  • Done that Pranav. One small help, I am wanting to put in "Last" in the detailedtableview, but its a float type number. Could you help me with the code. – Siddhant Mehandru Sep 09 '17 at 16:31
  • override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let item = self.listData[indexPath.row] cell.textLabel?.text = item["MarketName"] as? String cell.detailTextLabel?.text = item["Last"] as? String print(self.listData.count) return cell } – Siddhant Mehandru Sep 09 '17 at 16:32
  • when you run `cell.detailTextLabel?.text = String(item["Last"])` what error do you get? – Pranav Kasetti Sep 09 '17 at 16:55
  • cell.detailTextLabel?.text = item["Last"] as? String This doesnt give me any value showing cell.detailTextLabel?.text = String(item["Last"]) This says init has been renamed to init(describing) – Siddhant Mehandru Sep 09 '17 at 18:15
  • Ok keep your `as` statement. Make sure the style of your table view cell is set to subtitle. – Pranav Kasetti Sep 09 '17 at 18:40
  • Check this link: https://stackoverflow.com/questions/5190648/why-is-detailtextlabel-not-visible – Pranav Kasetti Sep 09 '17 at 19:26
  • Pranav, I have done that, it still doesnt show though. Must be some issue with the numeric form of the data being fetched into the table, because other data is being fetched into the table very easily – Siddhant Mehandru Sep 09 '17 at 19:54
  • Siddhant, please ask a separate question with your specific issue as I can't help you out through comments and I need more context. – Pranav Kasetti Sep 09 '17 at 20:45