I've made two functions which call two different rest APIs with an HTTP GET request. I've made a class call "ExchangeObject" which encapsulates the data retrieved from the APIs into an object. In each call, I append an object of class ExchangeObject to an array called exchangesArray.
One property of the ExchangeObject class is called "price" and it's an int value. In viewDidLoad, I call another function that calculates the average of the prices of the two objects in the array. However, the array is always empty! I don't know why. I think it's because I'm making asynchronous calls but I don't know how to fix it. However, my tableview isn't empty. It displays the two prices of the objects in the array.
class ViewController: UIViewController, UITableViewDataSource{
@IBOutlet weak var exchangesTableView: UITableView!
var exchangesArray = [ExchangeObject]()
override func viewDidLoad() {
super.viewDidLoad()
exchangesTableView.dataSource = self
gemini()
bitfinex()
average()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return exchangesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = exchangesTableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = exchangesArray[indexPath.row].name
cell?.detailTextLabel?.text = exchangesArray[indexPath.row].price
return cell!
}
func gemini(){
let url = "https://api.gemini.com/v1/pubticker/ethusd"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
let price = fetchedData["last"] as! String
self.exchangesArray.append(ExchangeObject(name: "Gemini", price: price))
DispatchQueue.main.async {
self.exchangesTableView.reloadData()
}
}
catch{
print("Error")
}
}
}
task.resume()
}
func bitfinex(){
let url = "https://api.bitfinex.com/v2/ticker/tETHUSD"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
let priceInt = fetchedData[6]
let price = String(describing: priceInt)
self.exchangesArray.append(ExchangeObject(name: "Bitfinex", price: price))
DispatchQueue.main.async {
self.exchangesTableView.reloadData()
}
}
catch{
print("Error")
}
}
}
task.resume()
}
func average() -> Void{
var total: Int = 0
var average: Int
for eth in self.exchangesArray{
total = total + Int(eth.price)!
}
average = total/self.exchangesArray.count
print("The average is: \(average)")
}
}
class ExchangeObject{
var name: String
var price: String
init(name: String, price: String){
self.name = name
self.price = price
}
}