数组作为参数不适用于Alamofire

时间:2018-10-27 10:57:50

标签: swift alamofire http-status-code-500

我有一个API,我需要在其中发送数据作为对象,因此我可以按以下方式传递数据,并且可以正常工作。

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

但是对于其中一种API,Web开发人员需要如下所示的API作为数组。

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

有什么想法吗?

下面是我的代码

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)

对于print,我得到的结果如下,表示我传递了正确的数据,但出现500错误。

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

知道我在做什么错吗?


编辑1

下面是Web开发人员需要的模型

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

1 个答案:

答案 0 :(得分:0)

答案是我需要如下添加ArrayEncoding。

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
}

现在添加扩展名

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
    }
}