Skip to content

Instantly share code, notes, and snippets.

@smosko
Last active September 22, 2018 06:59
Show Gist options
  • Save smosko/c583ce7433e0c2f3201be1fe87c314b2 to your computer and use it in GitHub Desktop.
Save smosko/c583ce7433e0c2f3201be1fe87c314b2 to your computer and use it in GitHub Desktop.
Generic NetworkService
import Foundation
public enum Result<Value> {
case success(Value)
case failure(Error)
}
public protocol Resource {
associatedtype Response
func makeRequest() -> URLRequest
func parseResponse(_ data: Data) throws -> Response
}
public final class NetworkService {
private let session: URLSession
public init(session: URLSession = .shared) {
self.session = session
}
@discardableResult
public func fetch<R: Resource>(_ resource: R, completion: @escaping (Result<R.Response>) -> Void) -> URLSessionTask {
let task = session.dataTask(with: resource.makeRequest()) { data, _, error in
if let error = error {
completion(.failure(error))
} else if let data = data {
do {
let response = try resource.parseResponse(data)
completion(.success(response))
} catch {
completion(.failure(error))
}
} else {
assertionFailure()
}
}
task.resume()
return task
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment