gpt4 book ai didi

swift - Alamofire 3 自定义编码到 Alamofire 4 自定义编码

转载 作者:搜寻专家 更新时间:2023-10-31 08:10:31 25 4
gpt4 key购买 nike

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

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版本?

最佳答案

只需分离 GET 和 POST 的结构也可以。

http://matsue.github.io/post/how-to-remove-square-brackets-with-alamofire/

Alamofire 4 与 Swift 3

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

// Remove square brackets for POST request
struct CustomPostEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try URLEncoding().encode(urlRequest, with: parameters)
let httpBody = NSString(data: request.httpBody!, encoding: String.Encoding.utf8.rawValue)!
request.httpBody = httpBody.replacingOccurrences(of: "%5B%5D=", with: "=").data(using: .utf8)
return request
}
}

// Use structs for requests
Alamofire.request("http://example.com", method: .get, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomGetEncoding())
Alamofire.request("http://example.com", method: .post, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomPostEncoding())

关于swift - Alamofire 3 自定义编码到 Alamofire 4 自定义编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40017640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com