Alamofire response object mapping

Syn3sthete picture Syn3sthete · Jun 1, 2017 · Viewed 10k times · Source

I am an android developer new to swift 3 programming, I am using Alamofire for making api calls and to avoid tedious json paring I am using AlamofireObjectMapper library. I have a ApiController which has a function to make api calls below is the code for that:

public static func makePostRequest<T: Mappable>(url: String, params: Parameters, networkProtocol: NetworkProtocol, responseClass: T){

    let headers = getHeaders()

    networkProtocol.showProgress()

    Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
        .validate()
        .responseData{ response in
            let json = response.result.value
            var jsonString = String(data: json!, encoding: String.Encoding.utf8)
            let responseObject = responseClass(JSONString: jsonString!)
            switch(response.result){
            case .success(_):
                networkProtocol.hideProgress()
                networkProtocol.onResponse(response: response)
                break
            case .failure(_):
                networkProtocol.hideProgress()
                networkProtocol.onErrorResponse(response: response)
                break
            }

    }

The Json response template I am getting from server is:

{
 "some_int": 10, 
 "some_array":[...]
}

Below is my model class:

import ObjectMapper

    class BaseResponse: Mappable {
    var some_int: Int?
    var some_array: [Array_of_objects]?

    required init?(map: Map) {
        some_int <- map["some_int"]
        some_array <- map["some_array"]
    }

    func mapping(map: Map) {

    }
}

And below is the function to class make the api call:

public static func callSomeApi(params: Parameters, networkProtocol: NetworkProtocol){
    ApiHelper.makePostRequest(url: AppConstants.URLs.API_NAME, params: params, networkProtocol: networkProtocol, responseClass: BaseResponse)
}

Now the error is in the below line

let responseObject = responseClass(JSONString: jsonString!)

I am not able to understand how to convert jsonString into the responseClass generic object which I am accepting from View controller

Someone please help me resolve this, stuck on this issue for quite a while now.

Answer

Sua Le picture Sua Le · Aug 21, 2018

You can use AlamofireMapper:

With json:

{
   "page":1,
   "per_page":3,
   "total":12,
   "total_pages":4,
   "data":[
      {
         "id":1,
         "first_name":"George",
         "last_name":"Bluth",
         "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
      },
      {
         "id":2,
         "first_name":"Janet",
         "last_name":"Weaver",
         "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"
      },
      {
         "id":3,
         "first_name":"Emma",
         "last_name":"Wong",
         "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"
      }
   ]
}

Swift class:

class UserResponse: Decodable {
    var page: Int!
    var per_page: Int!
    var total: Int!
    var total_pages: Int!

    var data: [User]?
}

class User: Decodable {
    var id: Double!
    var first_name: String!
    var last_name: String!
    var avatar: String!
}

Request with alamofire

let url1 = "https://raw.githubusercontent.com/sua8051/AlamofireMapper/master/user1.json"
        Alamofire.request(url1, method: .get
            , parameters: nil, encoding: URLEncoding.default, headers: nil).responseObject { (response: DataResponse<UserResponse>) in
                switch response.result {
                case let .success(data):
                    dump(data)
                case let .failure(error):
                    dump(error)
                }
        }

Link: https://github.com/sua8051/AlamofireMapper