swift - Alamofire 调用中的额外参数 'method' - 使用自定义 ParameterEncoding

标签 swift customization alamofire

我正在尝试上传 jsonSerialization 和 gzip 中的对象数组。我按照 github 中的描述编写了一个结构体。

struct JSONDocumentArrayEncoding: ParameterEncoding {
private let array: [Document]
init(array:[Document]) {
    self.array = array
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    var urlRequest = urlRequest.urlRequest

    let data = try JSONSerialization.data(withJSONObject: array, options: [])

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

    urlRequest!.httpBody = data

    return urlRequest!
}

}

然后在请求中

request = customAlamofireManager.request(
        ServerURL ,
        method: .post,
        parameters: [objects],
        encoding: JSONDocumentArrayEncoding,
        headers: headers
    )

错误是“调用中的额外参数方法”。这个问题在 github1508 here 中讨论过但我看不到解决方案。由于参数定义为[string:object],无法传入数组。因此,即使使用自定义的编码结构,也无法传入此正文数据。我在想一个解决方法可能是向数组添加一个虚拟键并修改服务器 api 以捕获字典的值。但没有理想。

最佳答案

回答我自己的问题:在不使用默认请求方法的情况下找到解决方法:

    func uploadBatchDocumentsWithDocs(_ documents: [Any]) {
        let headers = NetworkManager.sharedInstance.headers
         var urlRequest = URLRequest(url: URL(string: (ServerURL + Api))!)
         urlRequest.httpMethod = "post"
         urlRequest.allHTTPHeaderFields = headers
         let jsonArrayencoding = JSONDocumentArrayEncoding(array: documents)           
         let jsonAryEncodedRequest = try? jsonArrayencoding.encode(urlRequest, with: nil)

        var request: Alamofire.DataRequest? = customAlamofireManager.request(jsonAryEncodedRequest!)
        request?.validate{request, response, data in
            return .success
            }
            .responseJSON {
...
}

} 不要使用 request(url,method,parameters,encoding, headers),而是先手动创建encodedRequest,然后使用它来初始化 alamofire 的 datarequest。

关于swift - Alamofire 调用中的额外参数 'method' - 使用自定义 ParameterEncoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43165704/

相关文章:

ios - 如何在自定义 UITableViewCell 中获取 UILabel 的字体大小?

ios - Swift 2 中的 messageComposeViewController 错误

menu - 如何在 Liferay 控制面板中隐藏我的帐户 portlet 的选项卡

java - java中如何通过按钮最小化、最大化、向下还原?

ios - 在 swift alamofire 中创建 json 数组

ios - 显示来自非 UI 类的警报

javascript - 来自共享或操作扩展 ios 的网络请求

ios - 根据时间戳计算动画中风开始?

swift - 将值附加到 [String : AnyObject] or [String : String]