我想在textLabel&detailTextLabel中加载加密货币的名称和符号
TableViewController.swift:-
import UIKit
import Alamofire
import SwiftyJSON
class TableViewController: UITableViewController {
var fetchCoinInfo = [[String: AnyObject]]()
let url = "https://api.coinmarketcap.com/v1/ticker/"
override func viewDidLoad() {
super.viewDidLoad()
getCoinData(url: url)
self.tableView.reloadData()
}
// 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 fetchCoinInfo.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = fetchCoinInfo[indexPath.row]["name"] as? String
cell.detailTextLabel?.text = fetchCoinInfo[indexPath.row]["symbol"] as? String
return cell
}
使用阿拉莫菲尔:-
func getCoinData(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
print("Sucess! Got the data")
let coinJSON : JSON = JSON(response.result.value!)
print(coinJSON)
self.updateCoinData(json: coinJSON)
} else {
print("Error: \(String(describing: response.result.error))")
}
}
self.tableView.reloadData()
}
Using SwiftyJSON :-
func updateCoinData(json : JSON) {
if let coinData = json[].arrayObject {
print(coinData)
self.fetchCoinInfo = coinData as! [[String: AnyObject]]
}
else {
print("cannot connect to the server")
}
}
}
最佳答案
将这一行放入updateCoindataself.tableView.reloadData()
func updateCoinData(json : JSON) {
if let coinData = json[].arrayObject {
print(coinData)
self.fetchCoinInfo = coinData as! [[String: AnyObject]]
self.tableView.reloadData()
}
else {
print("cannot connect to the server")
}
}