Skip to content

Instantly share code, notes, and snippets.

@Que20
Created January 8, 2021 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Que20/c52c902a62c321528c88605a97cc1159 to your computer and use it in GitHub Desktop.
Save Que20/c52c902a62c321528c88605a97cc1159 to your computer and use it in GitHub Desktop.
// A simple network stack I use for my command line tools written in Swift.
// The dataTask here work only for GET operations.
protocol Operation {
associatedtype T: Codable
enum HTTPMethod {
case GET
case POST
case PUT
case DELETE
}
var url: URL { get set }
var method: HTTPMethod { get }
var params: [String : Any]? { get set }
var completion: (T?, OperationResponse?) -> () { get }
}
struct OperationResponse {
var statusCode: Int
var error: Error?
}
struct Network {
static func start<Op: Operation>(_ operation: Op) {
var keepAlive = true
URLSession.shared.dataTask(with: operation.url) { (data, res, err) in
Network.handleResponse(data, (res as? HTTPURLResponse), err, operation)
keepAlive = false
}.resume()
while keepAlive {
RunLoop.current.run(until: Date().addingTimeInterval(0.1))
}
}
private static func handleResponse<Op: Operation>(_ data: Data?, _ response: HTTPURLResponse?, _ error: Error?, _ operation: Op) {
let res = OperationResponse(statusCode: (response?.statusCode ?? -1), error: error)
func failed(response: OperationResponse) {
operation.completion(nil, res)
}
guard let data = data else { failed(response: res) ; return }
let decoded = try? JSONDecoder().decode(Op.T.self, from: data)
operation.completion(decoded, res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment