Skip to content

Instantly share code, notes, and snippets.

@IsaAliev
Created February 23, 2018 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IsaAliev/ae0626e4cc1ec4dda4541ec58d2ed451 to your computer and use it in GitHub Desktop.
Save IsaAliev/ae0626e4cc1ec4dda4541ec58d2ed451 to your computer and use it in GitHub Desktop.
import Foundation
enum HTTPMethod: String {
case GET
case POST
case PUT
case DELETE
}
protocol HTTPRequestRepresentable {
var path: String { get set }
var httpMethod: HTTPMethod { get }
var parameters: JSON? { get set }
var headerFields: [String: String]? { get set }
var bodyString: String? { get set }
}
extension HTTPRequestRepresentable {
func urlRequest() -> URLRequest? {
guard var urlComponents = URLComponents(string: self.path) else {
return nil
}
if let parametersJSON = self.parameters {
var queryItems = [URLQueryItem]()
for (key, value) in parametersJSON {
queryItems.append(URLQueryItem(name: key, value: value as? String))
}
urlComponents.queryItems = queryItems
}
guard let url = urlComponents.url else {
return nil
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = self.httpMethod.rawValue
urlRequest.allHTTPHeaderFields = headerFields
if let body = bodyString {
urlRequest.httpBody = body.data(using: .utf8)
}
return urlRequest
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment