【问题标题】:array as params is not working with Alamofire作为参数的数组不适用于 Alamofire
【发布时间】:2018-10-27 10:57:49
【问题描述】:

我有一个 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"
    }
]

【问题讨论】:

  • stackoverflow.com/questions/27026916/… stackoverflow.com/questions/30394112/… ...据我所知,Alamofire 本身并不管理数组参数。你必须自己做。
  • @Larme :这就是我在webParams2 所做的事情。但是还是有错误...
  • 您的服务器接受什么内容类型?大多数 JSON 内容类型都被接受。如果是这样,那么您应该写如下内容:var webParams2 : [String : Any] = ["array": array]
  • @AliMoazenzadeh :检查编辑 1 的 web 开发人员需要什么来发布请求...

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


【解决方案1】:

答案是我需要添加 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多