Update URLParameterEncoder.swift

This commit is contained in:
Jungpyo Hong 2021-05-19 23:13:58 -05:00 committed by GitHub
parent 274174ccdf
commit fa937ab0f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,27 +7,21 @@
import Foundation
public struct URLParameterEncoder: ParameterEncoder {
public func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {
struct URLParameterEncoder: ParameterEncoder {
static func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {
guard let url = urlRequest.url else { throw AppError.badUrl }
guard let url = urlRequest.url else { throw NetworkError.missingURL }
if var urlComponents = URLComponents(url: url,
resolvingAgainstBaseURL: false), !parameters.isEmpty {
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
urlComponents.queryItems = [URLQueryItem]()
for (key,value) in parameters {
let queryItem = URLQueryItem(name: key,
value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
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")
}
}
}