Skip to content

Instantly share code, notes, and snippets.

@ezequieloliveiralima
Created April 1, 2019 14:42
Show Gist options
  • Save ezequieloliveiralima/4f10dd0d061080fefdb2eba27e3c4570 to your computer and use it in GitHub Desktop.
Save ezequieloliveiralima/4f10dd0d061080fefdb2eba27e3c4570 to your computer and use it in GitHub Desktop.
import RxSwift
import RxCocoa
let BASE_URL = ""
enum HttpMethod: String {
case get = "GET"
case post = "POST"
}
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) -> Single<Data> {
#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
return URLSession.shared.rx.data(request: urlRequest).do(onNext: { data in
#if DEBUG
print("data size: \(data.count)")
#endif
}, onError: { error in
#if DEBUG
print("error: \(error?.localizedDescription ?? "without error")")
print("<<<<====")
#endif
}).asSingle()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment