I am trying to display the data from API . Here is the API Link .https://coinmap.org/api/v1/venues/ . I want to display the properties of the Vanues Array fields into IOS app . I created model by using Quick type . I use the Map like self.vanues = respone.results.map{$0} but still same result Here is the model .
import Foundation
// MARK: - Welcome
struct Coin: Codable {
let venues: [Venue]
}
// MARK: - Venue
struct Venue: Codable {
let id: Int
let lat, lon: Double
let category, name: String
let createdOn: Int
let geolocationDegrees: String
enum CodingKeys: String, CodingKey {
case id, lat, lon, category, name
case createdOn = "created_on"
case geolocationDegrees = "geolocation_degrees"
}
}
I convert that to list by using another swift file . Here is the code .
import Foundation
struct VanueResponse: Decodable {
let results: [Venue]
}
Here is my Network Manager .
import Foundation
class NetworkManager {
func getCoins(from url: String, completion: @escaping (Result<VanueResponse, NetworkError>) -> Void ) {
guard let url = URL(string: url) else {
completion(.failure(.badURL))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(.other(error)))
return
}
if let data = data {
//decode
do {
let response = try JSONDecoder().decode(VanueResponse.self, from: data)
completion(.success(response))
} catch let error {
completion(.failure(.other(error)))
}
}
}
.resume()
}
}
Here is the presenter class.
import Foundation
class VenuePresenter : VanueProtocol{
// creating instance of the class
private let view : VanueViewProtocol
private let networkManager: NetworkManager
private var vanues = [Venue]()
var rows: Int{
return vanues.count
}
// initilanize the class
init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
self.view = view
self.networkManager = networkmanager
}
func getVanue(){
let url = "https://coinmap.org/api/v1/venues/"
networkManager.getCoins(from: url) { result in
switch result {
case.success(let respone):
self.vanues = respone.results
DispatchQueue.main.async {
self.view.resfreshTableView()
}
case .failure(let error):
DispatchQueue.main.async {
self.view.displayError(error.localizedDescription)
print(Thread.callStackSymbols)
}
}
}
}
func getId(by row: Int) -> Int {
return vanues[row].id
}
func getLat(by row: Int) -> Double {
return vanues[row].lat
}
func getCreated(by row: Int) -> Int {
return vanues[row].createdOn
}
func getLon(by row: Int) -> Double? {
return vanues[row].lon
}
}
I put the break point and find this in console windows .
Here is the screenshot when I run the Applications .
CodePudding user response:
The Decoding Error is clear:
The key in the root dictionary is venues
(not results
) so the proper struct is Coin
.
In getCoins
replace both occurrences of VanueResponse
with Coin