Skip to content

Instantly share code, notes, and snippets.

@ezequieloliveiralima
Created April 1, 2019 14:36
Show Gist options
  • Save ezequieloliveiralima/1e20675e3c20381cf059d7a38193f477 to your computer and use it in GitHub Desktop.
Save ezequieloliveiralima/1e20675e3c20381cf059d7a38193f477 to your computer and use it in GitHub Desktop.
import Foundation
let BASE_URL = ""
enum HttpMethod: String {
case get = "GET"
case post = "POST"
}
protocol HttpObserver: AnyObject {
func httpUnknownError()
func http(error: String)
func http(statusCode: Int, data: Data)
}
struct Http {
let url: URL
let body: Data?
let method: HttpMethod
let headers: [ String: String ]
init(url: String, body: Data? = nil, method: HttpMethod = HttpMethod.get, headers: [ String: String ] = [:]) {
guard let url = URL(string: url) else {
fatalError("URL could not be infered.")
}
self.url = url
self.body = body
self.method = method
self.headers = headers
}
}
func request(http: Http, observer: HttpObserver) {
#if DEBUG
print("====>>>>")
print(http.url.absoluteString)
print("------------")
#endif
var urlRequest = URLRequest(url: http.url)
urlRequest.httpBody = http.body
urlRequest.httpMethod = http.method.rawValue
urlRequest.allHTTPHeaderFields = http.headers
let task = URLSession.shared.dataTask(with: urlRequest) { (data, urlResponse, error) in
#if DEBUG
print("data size: \(data?.count ?? 0)")
print("error: \(error?.localizedDescription ?? "without error")")
print("<<<<====")
#endif
guard let data = data else {
observer.httpUnknownError()
return
}
if let error = error {
observer.http(error: error.localizedDescription)
return
}
observer.http(statusCode: (urlResponse as! HTTPURLResponse).statusCode, data: data)
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment