Search code examples
swiftalamofire

Parse JSON - Alamofire


I'm trying to consume a Rest WebService...

My JSON response structure is:

"page": 1,
  "results": [
    {
      "poster_path": "/9Hj2bqi955SvTa5zj7uZs6sic29.jpg",
      "adult": false,
      "overview": "",
      "release_date": "2015-03-15",
      "genre_ids": [
        99
      ],
      "id": 441580,
      "original_title": "The Jinx: The Life and Deaths of Robert Durst Season 1 Chapter 6: What the Hell Did I Do?",
      "original_language": "en",
      "title": "The Jinx: The Life and Deaths of Robert Durst Season 1 Chapter 6: What the Hell Did I Do?",
      "backdrop_path": "/3br0Rt90AkaqiwVBZVvVUYD1juQ.jpg",
      "popularity": 1,
      "vote_count": 1,
      "video": false,
      "vote_average": 10
    }
],
  "total_results": 307211,
  "total_pages": 15361
}

I'm trying to get Page and Array of results...but page(paginationCount) and results(jsonArray) variable are nil after parse.

There's my code:

 Alamofire.request(ConstantHelper.kUrlDiscoverMovies, method: .get, parameters: ["api_key": ConstantHelper.kApiKey, "certification" : average, "sort_by" : "vote_average.desc" ]).validate()
            .responseJSON { response in
                switch response.result {
                case .success:
                    if let repoJSON = response.result.value as? JSON {
                        let jsonArray = repoJSON["results"] as? NSMutableArray
                        for item in jsonArray! {
                            guard let movie = Movie(json: item as! JSON) else
                            {
                                print("Issue deserializing model")
                                return
                            }
                            listMovies.append(movie)
                        }
                        if let paginationCount = repoJSON["total_pages"] as? String {
                            completion(listMovies, Int(paginationCount)!, nil)
                        }
                        else {
                            completion(listMovies, 0, nil)
                        }
                    }
                    break
                case .failure(let error):
                    completion(nil, 0, error as NSError?)
                    break
                }
        }

Solution

  • I don't know what type JSON is,

    but the value for key results is [[String:Any]], never NSMutableArray

    let jsonArray = repoJSON["results"] as? [[String:Any]]
    

    and the value for key total_pages is Int not String (there are no double quotes)

    if let paginationCount = repoJSON["total_pages"] as? Int {
        completion(listMovies, paginationCount, nil)
    }