iosjsonswiftalamofire

How to get a specific object from a JSON of an API in Xcode with Alamofire?


I am doing a project of an E-commerce app in swift and the data must be obtained from an API that I created with mockapi.io

The link of the API is: https://62858a2ff0e8f0bb7c057f14.mockapi.io/categorias but if you don't want to enter the link here is how the JSON looks like:

[
 {
  "categorie1": "Fruits",
  "categorie2": "Animals",
  "categorie3": "Juices",
  "categorie4": "Vegetables",
  "categorie5": "Alcohol",
  "categorie6": "Desserts",
  "id": "1"
 }
]

I have a file named "ResponseWS" that contains the structs to obtain the data from the API, it looks like this:

import Foundation

struct ResponseWS:Decodable{
    let Datos:[Categories]
}

struct Categories:Decodable{
    let id: String
    let categorie: String
}

I also have a file named "ConnectWS" where I process the data with the Alamofire:

import Foundation
import Alamofire

class ConnectWS{
    
    static let cmd = ConnectWS()
    private let urlBase = "https://62858a2ff0e8f0bb7c057f14.mockapi.io/categorias"
    private let code = 200...299
    
    func getUsers(user: String, pass: String,success: @escaping(_ user: String) -> (), failure: @escaping(_ error: Error?)-> ()) {
        
        AF.request(urlBase,method: .get).validate(statusCode: code).responseDecodable(of: ResponseWS.self){
            response in
            if let respuesta = response.data {
                
                print(String(decoding: respuesta, as: UTF8.self))
                success(String(decoding: respuesta, as: UTF8.self))
                
            }else{
                
                print(response.error!)
                failure(response.error)
                
            }
        }
    }
}

And finally I have my ViewController where I want to show the data of the API:

import UIKit

class ViewControllerCategorias: UIViewController {
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var message: UILabel!
    @IBOutlet weak var buttonOutlet: UIButton!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
      
    @IBAction func buttonAction(_ sender: Any) {
        ConnectWS.cmd.getUsers(user: "erik", pass: "1234", success: {user in
            self.name.text = user
        }, failure: {error in
            self.message.text = error.debugDescription
        })
    }
}

As you can see in the "ViewController" I have a button that when I click it, it returns ALL the data from the API, and what I want to do is get especifics "categories" from the API

When I click the button, the label shows:

[{"categorie1":"Fruits","categorie2":"Animals","categorie3":"Juices","categorie4":"Vegetables","categorie5":"Alcohol","categorie6":"Desserts","id":"1"}]

How can I get a specific object of the API?


Solution

  • You have to decode the response data into that object. You can use this generic method for decoding. Just create a model class/struct that you want to use for converting after decoding JSON.

    func decode<T: Codable>(_ data: Data) -> T {
        // Create a decoder
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        
        // Create a property for the decoded data
        guard let results = try? decoder.decode(T.self, from: data) else {
            fatalError("Failed to decode!")
        }
        // Return the ready-to-use data
        return results
    }