我可以在函數getJSON()中打印符號,但是當它顯示StockArray時,Nothing顯示,並且當我打印StockArray時,Nothing也會出現。我不知道這個問題。這是代碼。數據不顯示在UITableViewCell上Swift
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
}
}
謝謝。
注意:'cellForRowAtIndexPath'中的'StockArray.count!= 0'檢查是多餘的,因爲如果數組爲空,通常不會調用該方法。而是在'numberOfRowsInSection'中返回'StockArray.count',而不是準硬編碼的'NumberofRows' – vadian