Created
May 28, 2018 17:44
-
-
Save fmo91/078934b3d9f562466ef57220d7d15c59 to your computer and use it in GitHub Desktop.
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
public enum ConnError: Swift.Error { | |
case invalidURL | |
case noData | |
} | |
public struct URLSessionNetworkDispatcher: NetworkDispatcher { | |
public static let instance = URLSessionNetworkDispatcher() | |
private init() {} | |
public func dispatch(request: RequestData, onSuccess: @escaping (Data) -> Void, onError: @escaping (Error) -> Void) { | |
guard let url = URL(string: request.path) else { | |
onError(ConnError.invalidURL) | |
return | |
} | |
var urlRequest = URLRequest(url: url) | |
urlRequest.httpMethod = request.method.rawValue | |
do { | |
if let params = request.params { | |
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) | |
} | |
} catch let error { | |
onError(error) | |
return | |
} | |
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in | |
if let error = error { | |
onError(error) | |
return | |
} | |
guard let _data = data else { | |
onError(ConnError.noData) | |
return | |
} | |
onSuccess(_data) | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment