从API提取结构后,将结构保存到结构数组中时遇到问题。完成获取JSON数据并使用完成功能后,无法将数据附加到完成功能块内的数组中。我已经环顾了几天,尝试了很多事情,但仍然无法正常工作。
代码如下:
import UIKit
struct IndodaxApi:Decodable{
var ticker:dataStruct
}
struct dataStruct: Decodable {
var high:String
var low:String
var last:String
var vol_idr:String
var vol_btc:String
init(high:String, low:String, last:String, vol_idr:String, vol_btc:String) {
self.high = high
self.low = low
self.vol_idr = vol_idr
self.vol_btc = vol_btc
self.last = last
}
func printInfo() -> Void {
print("High:\(high)")
print("Low:\(low)")
print("Last:\(last)")
print("vol_idr:\(vol_idr)")
print("vol_btc:\(vol_btc)")
}
}
class data {
private let link:String
private let ticker:String
private let coinlist_idr:[String]
private var dataCoin:[dataStruct]
init() {
link = "https://indodax.com/api/"
ticker = "/ticker"
coinlist_idr = ["btc_idr"]
dataCoin = [dataStruct]()
}
public func getData() -> [dataStruct] {
dataCoin.removeAll()
load()
return dataCoin
}
此功能意味着将从completionhandler返回的数据附加到作为DataStruct结构的dataCoin数组中:
private func load(){
var index = 0
let totalCoin = coinlist_idr.count
while(index<totalCoin){
fetchcoin(coinName: getNextCoin(index), completionHandler: { (data) in
self.dataCoin.append(data)
})
index+=1
}
}
这里的功能是从API获取数据并将其传递给完成处理程序:
public func fetchcoin(coinName:String, completionHandler: @escaping ((dataStruct)->Void)){
let urlLink = self.link + coinName + self.ticker;
let url = URL(string: urlLink)
URLSession.shared.dataTask(with: url!) { (data, response, err) in
guard let data = data else {return}
do {
let api = try JSONDecoder().decode(IndodaxApi.self, from: data)
DispatchQueue.main.async {
let returnData = dataStruct(high: api.ticker.high, low: api.ticker.low, last: api.ticker.last, vol_idr: api.ticker.vol_idr, vol_btc: api.ticker.vol_btc)
completionHandler(returnData)
}
}catch let jsonERR{
print(jsonERR)
}
}.resume()
}
private func getNextCoin(_ coinName:Int)->String{
return coinlist_idr[coinName]
}