I want to make a Swift (5.4.6) app to display information about cryptos. For this I need to call a server to get the information I want to display. However my application don't wait for the data to be processed so I get an error for wanting to display a nil.
Here is my code for the call to the server :
var cryptos = Cryptos(cryptos: nil)
let url = URL(string: urlString)
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) {(data, response, error) in
if error == nil && data != nil {
let decoder = JSONDecoder()
do {
cryptos = try decoder.decode(Cryptos.self, from: data!)
print(cryptos.cryptos![6].name)
}
catch {
print("Impossible de convertir les données reçues")
}
}
}
dataTask.resume()
return cryptos
}
Here are the struct I want to decode the json into :
struct Crypto: Codable {
let name: String
let symbol: String
let price: Float
let totalSupply: Float
let marketCap: Float
let change24h: Float
}
struct Cryptos: Codable {
let cryptos: [Crypto]?
}
Finally here is the code in my view :
var lesCryptos = Cryptos()
struct CryptoList: View {
var body: some View {
HStack {
NavigationView {
}
}
.onAppear(perform: getAllCryptosInfos)
}
}
func getAllCryptosInfos() {
lesCryptos = Worker().getAllCryptosInfos()
print(lesCryptos.cryptos![7].name)
}
The error appears when I want to print the name ("lesCryptos.cryptos!" is nil)
Also here is a sample of the JSON i get :
{
"cryptos": [
{
"name":"Bitcoin",
"symbol":"BTC",
"price":36301.41347043701,
"totalSupply":18728856,
"marketCap":679883945484.275,
"change24h":0.36443243
},
{
"name":"Ethereum",
"symbol":"ETH",
"price":2784.5450982190573,
"totalSupply":116189845.499,"marketCap":323535864747.07007,
"change24h":3.46116544
}
]
}