Home > Net >  The data couldn't be read because it isn't in the correct format
The data couldn't be read because it isn't in the correct format

Time:05-21

Hello I am creating an app with Xcode and I am having the following problem, I created this API with mockapi.io (if you enter the link you'll see the JSON data) https://62858a2ff0e8f0bb7c057f14.mockapi.io/categorias

If you dont want to enter the link here is how it looks the JSON: (By default the JSON has an array without name as the root and that can't be modified)

[
   {
      "categorie":"Fruits",
      "id":"1"
   },
   {
      "categorie":"Animals",
      "id":"2"
   },
   {
      "categorie":"Vegetables",
      "id":"3"
   },
   {
      "categorie":"Juices",
      "id":"4"
   },
   {
      "categorie":"Alcohol",
      "id":"5"
   },
   {
      "categorie":"Desserts",
      "id":"6"
   }
]

The problem I have is that when I try to decode the data from the API it cant't be readed because is in the wrong format, I am trying to recreate the same code of this youtube video, but with my API: https://www.youtube.com/watch?v=sqo844saoC4

This is how my code looks like:

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = "https://62858a2ff0e8f0bb7c057f14.mockapi.io/categorias"
        getData(from: url)
    } 
    private func getData(from url: String) {   
        let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
            guard let data = data, error == nil else {
                print("something went wrong")
                return
            }   
            var result: Response?
            do {
                result = try JSONDecoder().decode(Response.self, from: data)
            }
            catch {
                print("failed to convert\(error.localizedDescription)")
            }      
            guard let json = result else {
                return
            } 
            print(json.items.categorie) //            
  • Related