Search code examples
iosjsonswiftalamofire

Getting array of objects from CodableAlamofire


Im using Alamofire with the CodableAlamofire extension but I having trouble in get one data in my json response.

This is my json:

{
    "total": 95,
    "per_page": 100,
    "current_page": 1,
    "last_page": 1,
    "from": 1,
    "to": 95,
    "data": [
        {
            "id": 1,
            "name": "ONE",
            "city": "CITY 1"
        },
        {
            "id": 2,
            "name": "TWO",
            "city": "CITY 2"
        },
        {
            "id": 3,
            "name": "THREE",
            "city": "CITY 3"
        }
    ]
}

I have these structs:

struct AssetResult: Decodable {
    let current_page : Int
//    let data : [AssetData]
    let from : Int
    let last_page : Int
    let per_page : Int
    let to : Int
    let total : Int


    enum CodingKeys : String, CodingKey {
        case current_page
//        case data
        case from
        case last_page
        case per_page
        case to
        case total
    }
}

struct AssetData: Decodable {
    let city : String
    let id : String
    let name : String
}

And this is the code to get the data in AssetResult struct:

let parameters: Parameters = ["page": 1]
let url = URL(string: "http://url")!
let decoder = JSONDecoder()

Alamofire.request(url, parameters: parameters).responseDecodableObject(keyPath: nil, decoder: decoder) { (response: DataResponse<AssetResult>) in
            let repo = response.result.value
            print(repo)
        }

The problem is everytime I try to get the data (uncommenting the data in the AssetResult struct) the print(repo) turn to nil.

If I let the data commented this is printed:

Optional(AssetResult(current_page: 1, from: 1, last_page: 1, per_page: 100, to: 95, total: 95))

How can I get the array of objects? Preferably as an array of AssetData objects.

Thanks


Solution

  • I ran several tests with the JSON return and realized that some assets appeared without a city, which caused the error:

    {
        "id": 10,
        "name": "TEN",
        "city": null
    },
    

    So I just needed change the city to optional, adding the ? after the type:

    struct AssetData: Decodable {
        let city : String?
        let id : String
        let name : String
    }