我制作了两个函数,它们通过 HTTP GET 请求调用两个不同的 rest API。我创建了一个名为“ExchangeObject”的类,它将从 API 检索到的数据封装到一个对象中。在每次调用中,我将一个 ExchangeObject 类的对象附加到一个名为 exchangeArray 的数组中。
ExchangeObject 类的一个属性称为“价格”,它是一个 int 值。在 viewDidLoad 中,我调用另一个函数来计算数组中两个对象的平均价格。但是,数组总是空的!我不知道为什么。我认为这是因为我正在进行异步调用,但我不知道如何修复它。但是,我的 tableview 不是空的。它显示数组中对象的两个价格。
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
}
}