Alamofire 3自定义编码到Alamofire 4自定义编码 [英] Alamofire 3 Custom Encoding To Alamofire 4 Custom Encoding

查看:259
本文介绍了Alamofire 3自定义编码到Alamofire 4自定义编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Alamofire 3中使用customParameterEncoding编写方法。这种自定义编码只是将queryString中的 [] =替换为 =并返回。

I have method writing in Alamofire 3 with customParameterEncoding. This custom encoding just replaces "[]=" with "=" in queryString and returns it.

Alamofire.request(.GET, SearchURL, parameters: params, encoding: customEncoding, headers: headers).validate().responseJSON {
            response in
            switch response.result {
            case .success:
                print("success")
                break
            case .failure(let error):
                print("Error: " + error.localizedDescription)
                break
            }
        }

和自定义编码参数

let customEncoding =  ParameterEncoding.Custom { requestConvertible, parameters in
    let (mutableRequest, error) = ParameterEncoding.URL.encode(requestConvertible, parameters: parameters)
    mutableRequest.URL = NSURL(string: mutableRequest.URLString.stringByReplacingOccurrencesOfString("%5B%5D=", withString: "="))
    return (mutableRequest, error)
}

如何将customEncoding转换为Alamofire 4版本? / p>

How to convert customEncoding to Alamofire 4 version?

推荐答案

在Alamofire 4.0中,您应该使用 ParameterEncoding

In Alamofire 4.0 you should use ParameterEncoding.

struct CustomEncoding: ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try! URLEncoding().encode(urlRequest, with: parameters)
        let urlString = request.url?.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "=")
        request.url = URL(string: urlString!)
        return request
    }
}

这篇关于Alamofire 3自定义编码到Alamofire 4自定义编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆