Created
May 16, 2019 14:12
-
-
Save wddwycc/26df51cfc390eb0b00764b7d11b33ed0 to your computer and use it in GitHub Desktop.
simple but full featured http client based on Rx
This file contains hidden or 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 | |
| import RxSwift | |
| import RxCocoa | |
| class HTTPClient { | |
| private let session = URLSession.shared | |
| func request(_ method: String = "GET", url: String, | |
| params: [String: String]? = nil, headers: [String: String]? = nil) -> URLRequest? { | |
| guard let fullURL = { () -> URL? in | |
| if let params = params, var urlComps = URLComponents(string: url) { | |
| urlComps.queryItems = params.map { URLQueryItem(name: $0.key, value: $0.value) } | |
| return urlComps.url | |
| } else { | |
| return URL(string: url) | |
| } | |
| }() else { return nil } | |
| var req = URLRequest(url: fullURL) | |
| req.httpMethod = method | |
| if let headers = headers { | |
| for (k, v) in headers { | |
| req.addValue(v, forHTTPHeaderField: k) | |
| } | |
| } | |
| return req | |
| } | |
| func task(request: URLRequest) -> Observable<Data> { | |
| return Observable.deferred { self.session.rx.data(request: request) } | |
| } | |
| func task<T: Codable>(request: URLRequest, decodeWith: T.Type) -> Observable<T> { | |
| return task(request: request).map { data in | |
| let decoder = JSONDecoder() | |
| return try decoder.decode(T.self, from: data) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment