i'm using Moya library to calling api in my project.
now one of apis required to pass raw json object(multiples object as single object) with POST request in body. it is working fine in postman.
check below screenshot,
also check raw body json,
{
"geometry": {
"location": {
"lat": "22.7195687",
"lng": "75.8577258"
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/geocode-71.png",
"name": "Indore",
"photos": [
{
"photo_reference": "Aap_uECCOLowEnJ2yBUzF0nwRjV5jBx2_JWsofVosuLVvlr-ClIMHNR5-QGIe4phK-3_Bj_laHD_XH_LvlmGDzm33KvxuO1XzaZocxTLOVUdSGI3_otXvpx_FbuzmwiibZiylQEMkekTLKbLdXjK8H3w10nOcoJE-InDVvf5P7Cvyum_kk9k"
}
],
"place_id": "ChIJ2w1BG638YjkR9EBiNdrEbgk",
"reference": "ChIJ2w1BG638YjkR9EBiNdrEbgk",
"types": [
"locality",
"political"
],
"vicinity": "Indore"
},
{
"geometry": {
"location": {
"lat": "22.7429365",
"lng": "75.8867267"
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_business-71.png",
"name": "Visual Maker",
"photos": [
{
"photo_reference": "Aap_uED84yCmvAirxt-dSdPPSE3O_eBSunEiSOM1Uzr0kNNMiJBVvPtBuCuwck2Ek0CDg7S8JP09Iva3Rjhq63O1Tyql_CTeMRF_GWC19QfZUFwwvadcRbfLWo6Wqn4ndCTCh5A6RV212PJcB0HZqe6YV7FphiV_XjkP9pCvk5JLDKNrvOXz"
}
],
"place_id": "ChIJGwLEIlr9YjkRnr8uTQiQ8KU",
"reference": "ChIJGwLEIlr9YjkRnr8uTQiQ8KU",
"types": [
"university",
"general_contractor",
"point_of_interest",
"establishment"
],
"vicinity": "behind Anop Cinema, K/112, LIG Colony, Indore"
},
}
this is two object but it can be multiples objects
below is my Moya class for api calling.
import Moya
import Result
import Alamofire
import UIKit
private func JSONResponseDataFormatter(_ data: Data) -> Data {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data)
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
return prettyData
} catch {
return data // fallback to original data if it can't be serialized.
}
}
private extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
}
let MyAPIProvider = MoyaProvider<EBabuAPI>( plugins: [VerbosePlugin(verbose: true)])
enum MyAPI {
case topPlaceVibeAvg(geometry : [Any], icon:[String], name:[String], photos:[Any], placeIds:[String], reference:[String], types:[Any], vicinity:[Any])
}
extension EBabuAPI: TargetType {
var headers: [String : String]? {
switch self {
default:
return ["Authorization": SharedPreference.authToken()]
}
}
var baseURL : URL {
return URL(string: Constants.API.baseURL)! //["Authorization": "Bearer \(Helpers.userToken())"]
}
var path: String {
switch self {
case .topPlaceVibeAvg:
return "places/topPlaceVibeAvg"
}
}
public var method: Moya.Method {
switch self {
case .topPlaceVibeAvg :
return .post
}
}
var sampleData: Data {
return "".data(using: .utf8)!
}
var task: Task {
switch self {
case .topPlaceVibeAvg(let geometry,let icon, let name, let photos, let placeIds, let reference, let types, let vicinity):
return .requestParameters(parameters: ["geometry":geometry, "icon":icon, "name":name, "photos":photos, "place_id":placeIds, "reference":reference, "types":types, "vicinity":vicinity], encoding: JSONEncoding.default)
}
}
func dicToStrig(data : AnyObject) -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: data, options: [])
let jsonString = String(data: jsonData, encoding: String.Encoding.ascii)!
return jsonString
} catch {
//handle error
print("error",error)
}
return ""
}
var parameterEncoding: ParameterEncoding {
switch self {
default:
return JSONEncoding.default
}
}
}
struct JsonArrayEncoding: Moya.ParameterEncoding {
public static var `default`: JsonArrayEncoding { return JsonArrayEncoding() }
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var req = try urlRequest.asURLRequest()
let json = try JSONSerialization.data(withJSONObject: parameters!["jsonArray"]!, options: JSONSerialization.WritingOptions.prettyPrinted)
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.httpBody = json
return req
}
}
as everyone can see above code i'm trying to call topPlaceVibeAvg api with their keys & values api calling successfully but it does not provide proper response same as postman screenshot.
here is api Response: { data = ( ); message = "average fetched successfully!"; statusCode = 200; success = 1; }
i'm using below ViewModel(placesViewModel) to call api.
var icon = [String]()
var name = [String]()
var name = [Any]()
var placeIds = [String]()
var reference = [String]()
var testTypes = [Any]()
var vicinity = [Any]()
var geometry = [Any]()
var photos = [Any]()
func topPlaceVibeAvg(_ completion: @escaping ((JSONDictionary) -> ())) {
if !isPullToRefresh { Loader.show("Looking around....") }
APIController.makeRequest(.topPlaceVibeAvg(geometry: geometry, icon: icon, name: name, photos: photos, placeIds: placeIds, reference: reference, types: types, vicinity: vicinity)) { (data, error) in
Loader.hide()
if error == nil {
completion(data!)
} else {
ToastAndAlertManager.showToastWithTitle((error?.desc)!, colorCode: ToastColor.error.rawValue)
}
}
}
here is my ViewController class for api
placesViewModel.geometry = self.nearByPlacesArray.map{$0.geometry}
placesViewModel.icon = self.nearByPlacesArray.map{$0.icon}
placesViewModel.name = self.nearByPlacesArray.map{$0.name}
placesViewModel.photos = self.nearByPlacesArray.map{$0.photos}
placesViewModel.placeIds = self.nearByPlacesArray.map{$0.placeId}
placesViewModel.reference = self.nearByPlacesArray.map{$0.reference}
placesViewModel.testTypes = self.nearByPlacesArray.map{$0.types}
placesViewModel.vicinity = self.nearByPlacesArray.map{$0.vicinity}
placesViewModel.topPlaceVibeAvg { (data) in
print(data)
}
Note : **nearByPlacesArray** is main array & i'm to sorting my required array object from here
I'm really tried with problem, i've already search regarding this thing but got no answers.
AnyOne have idea about this?

To send complex parameters in the request body you can use the Moya function:
Moya have this comment for this function:
So this function allow us send anything in the request body.
For example something like this is a good aproach: