Last active
September 22, 2018 06:59
-
-
Save smosko/c583ce7433e0c2f3201be1fe87c314b2 to your computer and use it in GitHub Desktop.
Generic NetworkService
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 | |
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