0

I have an API where I need to send data as object so there I pass data as below and it works fine.

["fname" : "First 1", "lname": "Last 1"]

But for one of the API, web developer need API as Array as below.

[["fname" : "First 1", "lname": "Last 1"]]

Any idea what is going wrong?

Below is the code I have

parameters = ..... data that I passed as [String : Any] // e.x. ["fname" : "First 1", "lname": "Last 1"]

var finalWebParams : Any

var webParams2 : [[String : Any]] = [[String : Any]]()
if (webserviceFor=="array") {
    webParams = parameters as [String:Any]
    webParams2.append(webParams)
}

if (webserviceFor=="array") {
    finalWebParams = webParams2
} else {
    finalWebParams = webParams
}

print("finalWebParams==\(finalWebParams)")

request(url, method: webMethod, parameters: finalWebParams as? Parameters, encoding: myEncoding, headers: headers)

For print I get result as below, means I am passing correct data however I get 500 error.

[["fname" : "First 1", "lname": "Last 1"]]

Any idea what I am doing wrong?


Edit 1

below is the model that web developer need

[
    {
        "fname" : "First 1",
        "lname" : "Last 1"
    }
]
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
  • https://stackoverflow.com/questions/27026916/sending-json-array-via-alamofire https://stackoverflow.com/questions/30394112/how-do-i-use-json-arrays-with-alamofire-parameters ... From what I remember Alamofire doesn't manage array parameter itself. You have to do it yourself. – Larme Oct 27 '18 at 11:00
  • @Larme : That is what I am doing in `webParams2`. But still have error... – Fahim Parkar Oct 27 '18 at 11:08
  • What content type your server accepts? mostly JSON content types are accepted. if this then you should write something like: `var webParams2 : [String : Any] = ["array": array] ` – Ali Moazenzadeh Oct 27 '18 at 11:46
  • @AliMoazenzadeh : check Edit 1 of what web developer need for the post request... – Fahim Parkar Oct 27 '18 at 12:06

1 Answers1

0

The answer is I need to add ArrayEncoding as below.

var finalWebParams : [String : Any]

var webParams2 : [[String : Any]] = [[String : Any]]()
if (webserviceFor=="array") {
    webParams = parameters as [String:Any]
    webParams2.append(webParams)
}

if (webserviceFor=="array") {
    finalWebParams = webParams2.asParameters()
} else {
    finalWebParams = webParams
}

Now add extension

private let arrayParametersKey = "arrayParametersKey"

/// Extenstion that allows an array be sent as a request parameters
extension Array {
    /// Convert the receiver array to a `Parameters` object.
    func asParameters() -> Parameters {
        return [arrayParametersKey: self]
    }
}


/// Convert the parameters into a json array, and it is added as the request body.
/// The array must be sent as parameters using its `asParameters` method.
struct ArrayEncoding: ParameterEncoding {

    /// The options for writing the parameters as JSON data.
    public let options: JSONSerialization.WritingOptions


    /// Creates a new instance of the encoding using the given options
    ///
    /// - parameter options: The options used to encode the json. Default is `[]`
    ///
    /// - returns: The new instance
    public init(options: JSONSerialization.WritingOptions = []) {
        self.options = options
    }

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        guard let parameters = parameters,
            let array = parameters[arrayParametersKey] else {
                return urlRequest
        }

        do {
            let data = try JSONSerialization.data(withJSONObject: array, options: options)

            if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
                urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
            }

            urlRequest.httpBody = data

        } catch {
            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
        }

        return urlRequest
    }
}
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276