How to use AlamofireObjectMapper?
If you are using Alamofire for Networking in Swift, this article will be helpful for you.
AlamofireObjectMapper is an extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper
Usage
AlamofireObjectMapper can be installed via Cocoapods or Carthage
Consider following sample JSON returned from an API
It returns an array of Projects along with some data relevant to it. Now I want to map this response directly to an array of custom object of type Project.
To map this response to our model class, we need our model class Project to conform to the Mappable protocol. Please find below how I defined Project model class. I have defined only relevant information I want to map.
Note: You can use this JSONExport utility application available for mac which helps to auto-generate model classes for various formats.
AlamofireObjectMapper extension provides various ways to access response data.
- Directly map response to your model object if you wish to map entire response
Alamofire.request(URL).responseObject { (response: DataResponse) in
let projectResponse = response.result.value
}
Here ProjectResponse will be your model object which will conform to the mappable protocol to map the entire response mentioned about.
2. Using Keypath to access required data. For e.g we want to access the result array. So, we can use keypath along with the responseArray function of AlamofireObjectMapper extension as follow:
Alamofire.request(URL).responseArray(keyPath: "result") { (response: DataResponse<[Project]>) in
let projects = response.result.value
}
You can find below working snippet of the function:
Don’t get confused by `.validate()` in above code. It is Alamofire function which validates the success or failure of a request based on HTTP Code.
AlamofireObjectMapper Vs SwiftyJSON
Now you might be confused whether to use AlamofireObjectMapper of SwiftyJSON? In fact, you can use both together also. SwiftyJSON is still helpful for you where you don’t want to create model classes and just want to retrieve values on demand from the response for e.g. checking status, error or getting pageSize of the response.
You can find the sample project for above example over here
Do comment if you have any questions or suggestions.