I am going to decode a Magic cards database from a JSON file fetched from this API (here). however, an error appears when I try to plot some data in the canvas with SwiftUI.
I thought I might do something worry when I called the FetchdAndDecodedMtgData model at the first time. But I got confused when I set some print() debugger in my FetchdAndDecodedMtgData model because these debuggers don't print anything in the debug monitor.
I don't know how to solve it. If the FetchdAndDecodedMtgData model is correct, then how to call the decodedData in the ContentView?
Any help is appreciated!
The FetchdAndDecodedMtgData model
struct FetchdAndDecodedMtgData {
let urlString: String
var url: URL?
init(urlString: String) {
self.urlString = urlString
url = URL(string: urlString) ?? nil
}
func fetchdAndDecodeApiData(completion: @escaping (MTGData?, Error?) -> ()) {
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
if let error = error {
completion(nil, error)
print("! Error")
return
}
//check response status code etc if needed
//parse data
guard let data = data else {
completion(nil, NameError.invalidData)
print("! Error")
return
}
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode(MTGData.self, from: data)
print(decodedData)
DispatchQueue.main.async {
completion(decodedData, nil)
}
} catch {
completion(nil, error)
}
}
task.resume()
}
}
The ContentView:
struct ContentView: View {
static let urlString: String = "https://mtgjson.com/api/v5/YNEO.json"
let fetchdAndDecodedModel: FetchdAndDecodedMtgData = FetchdAndDecodedMtgData(urlString: urlString)
@State var mtgData: MTGData!
var body: some View {
VStack {
Text("API retrive date: \(mtgData.meta.date)")
.padding()
Text("API retrive version: \(mtgData.meta.version)")
.padding()
Divider()
Text("Card Number: \(mtgData.data.baseSetSize)")
}
.onAppear() {
fetchdAndDecodedModel.fetchdAndDecodeApiData { (result, error) in
self.mtgData = result!
}
}
}
}