I have created a UITableview and added a few cells displaying the names of a couple of stocks(Apple, Tesla). I also added a right-detail text label to my cells in which I want to display the current stock price of the stocks. So far, using Finnhub.io, I was able to create an API call and store the current price data in a variable called decodedData. I was also able to print out that data in my debug console. The only problem that I'm currently facing is not showing the debug console's data in the UI cells. If anyone has any ideas on how to solve this issue, please let me know.
Here is my code for making the API call and getting the URL:
struct StockManager {
let decoder = JSONDecoder()
var returnValue:String = ""
let stockUrl = "https://finnhub.io/api/v1/quote?token=AUTH_TOKEN"
mutating func fetchStock(stockName: String) -> String{
var stockValue:String = ""
let urlString = "\(stockUrl)&symbol=\(stockName)"
stockValue = performRequest(urlString: urlString)
return stockValue
}
func performRequest(urlString: String) -> String {
var retValue: String = ""
//Create a URL
if let url = URL(string: urlString){
//Create a url session
let session = URLSession(configuration: .default)
//Create task
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil{
print(error)
return
}
if let safeData = data{
self.parseJSON(stockData: safeData)
}
//Start task
}
task.resume()
}
return retValue
}
func parseJSON(stockData: Data) -> String {
var returnValue: String = ""
var jsonValue: String = ""
do{
let decodedData = try decoder.decode(StockData.self, from: stockData)
let c:String = String(decodedData.c)
let h:String = String(decodedData.h)
let l:String = String(decodedData.l)
jsonValue = String(decodedData.c)
print(decodedData.c)
// let stockData = StockData(c: c, h: h, l: l)
}catch{
print("Error decoding, \(error)")
}
return jsonValue
}
}
And here is my code for creating the table view and cells:
var listOfStocks = ["AAPL", "TSLA"]
var listOfStocks2 = ["Apple": "AAPL", "Tesla": "TSLA"]
var stockManager = StockManager()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listOfStocks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create cell
let cell = tableView.dequeueReusableCell(withIdentifier: "StockListCell", for: indexPath)
let jsonValue: String = ""
cell.textLabel?.text = listOfStocks[indexPath.row]
if let stock = cell.textLabel?.text{
stockManager.fetchStock(stockName: stock)
cell.detailTextLabel?.text = stock
}
return cell
}
I want to be able to show my current stock price by coding in the function above (override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)). Please let me know if anyone has an answer to this issue, thanks!