我有一个具有很多属性的模型,我想将该模型编码为url查询参数。
public typealias Parameters = [String : Any]
enum ProductWriteApi {
case addOFFProduct(product: OFFProduct)
}
extension ProductWriteApi: EndPointType {
var parameters: Parameters {
switch self {
case .addOFFProduct(let product):
var parameters: Parameters!
do {
//Need to encode the product model to be like the Example parameters down there.
let data = try JSONEncoder().encode(product)
//This data wont be sent in the body. It will be sent in the URL.
} catch {
}
//Example parameters needed
parameters = [
"name": "Cereal",
"categorie": "Milks"
]
return parameters
}
}
}
因此,我如何才能将产品模型更改/编码为[String : Any]
,以便能够遍历它们并将其添加到我的url字符串中。
还是我必须逐个传递每个产品属性,然后检查它是否不是nil
也不为空并将其添加到[String : Any]
类型的变量中?
还是有我不知道的另一种更简单的解决方案?
这是一个静态函数,它通过遍历参数并将其附加到查询项中来将参数添加到我的url中。
public struct URLParameterEncoder: ParameterEncoder {
public static func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {
guard let url = urlRequest.url else { throw NetworkError.missingURL}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
urlComponents.queryItems = [URLQueryItem]()
for (key,value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))
urlComponents.queryItems?.append(queryItem)
}
urlRequest.url = urlComponents.url
}
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
}
}