Patty Patty - 4 months ago 14
iOS Question

Data is not displaying on UITableViewCell Swift

I can print the symbols in the function getJSON(), but when it comes time to displaying the StockArray, Nothing appears, and when I print StockArray, Nothing appears as well. I do not know the problem. Here is the code.

import UIKit
import Alamofire
import ObjectMapper
import SwiftyJSON

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

var NumberofRows = 0
let stockURL = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL+TSLA%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json"
var StockArray = [String]()




@IBOutlet weak var tableView: UITableView!

// @IBOutlet weak var StockSymbolLbl: UILabel!
// @IBOutlet weak var BidSymbolLbl: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
getJSON()
// StockSymbolLbl.text = ""
// BidSymbolLbl.text = ""


}

func getJSON(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let url = NSURL(string: self.stockURL)
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 Symbol: String? = swiftyJSON["query"]["results"]["quote"][0]["symbol"].stringValue
let bid: String? = swiftyJSON["query"]["results"]["quote"][0]["Change"].stringValue
print(Symbol!)
print(bid!)
dispatch_async(dispatch_get_main_queue()) {
// self.StockSymbolLbl.text? = "\(Symbol!)"
// self.BidSymbolLbl.text? = "\(bid!)"
self.NumberofRows = swiftyJSON["query"]["results"]["quote"].count

for i in 0...self.NumberofRows {
var stockcount = 0
stockcount += i
let Stock = swiftyJSON["query"]["results"]["quote"][stockcount]["symbol"].stringValue
self.StockArray.append(Stock)
print(Stock)
}

}



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

}
task.resume()
}

}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NumberofRows
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

if StockArray.count != 0{
cell.textLabel?.text = StockArray[indexPath.item]
}

print(self.StockArray)

return cell
}



}


Thank you.

Answer

Have you tried calling reload data in getJSON() after the loop?

                for i in 0...self.NumberofRows {
                    var stockcount = 0
                    stockcount += i
                    let Stock = swiftyJSON["query"]["results"]["quote"][stockcount]["symbol"].stringValue
                    self.StockArray.append(Stock)
                    print(Stock)
                }
              tableView.reloadData() 
            }