I can't run my built app because I have:
Unexpectedly found nil while unwrapping an Optional value
on self.tableView.reloadData()
.
I connected to API using Alamofire and SwiftyJson, and also connected tableView outlet.
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var coinData: [CoinModel] = []
override func viewDidLoad() {
super.viewDidLoad()
fetchCoinData()
}
func fetchCoinData() {
DispatchQueue.main.async {
Alamofire.request("https://api.coincap.io/v2/markets").responseJSON(completionHandler: { (response) in
switch response.result {
case.success(let value):
let json = JSON(value)
let data = json["data"]
data.array?.forEach({ (user) in
let user = CoinModel(coin: user["baseSymbol"].stringValue,coinName: user["baseId"].stringValue, coinPrice: user["priceUsd"].stringValue)
self.coinData.append(user)
print(user.coin)
print(user.coinPrice)
print(user.coinName)
//print(data)
})
self.tableView.reloadData()
case.failure(let error):
print(error.localizedDescription)
}
})
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.coinData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CoinTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? CoinTableViewCell else {
fatalError("The dequeued cell is not an instance of CoinTableViewCell.")
}
tableView.backgroundColor = .clear
cell.backgroundColor = .clear
tableView.tableFooterView = UIView()
let coin = coinData[indexPath.row]
cell.coinLabel.text = coin.coin
cell.coinNameLabel.text = coin.coinName
cell.coinPriceLabel.text = coin.coinPrice
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}