awesome-ios-developer/Helper/Network Layer/Encoding/URLParameterEncoder.swift
2021-05-03 01:33:13 -05:00

34 lines
1.1 KiB
Swift

//
// URLParameterEncoder.swift
// MapDemoApp
//
// Created by JungpyoHong on 4/25/21.
//
import Foundation
public struct URLParameterEncoder: ParameterEncoder {
public 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), !parameters.isEmpty {
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")
}
}
}