Created
February 23, 2018 18:57
-
-
Save IsaAliev/ae0626e4cc1ec4dda4541ec58d2ed451 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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