Skip to content

Instantly share code, notes, and snippets.

@ashalva
Last active July 26, 2018 06:07
Show Gist options
  • Save ashalva/646bd5e62d67fea98c55fa420b86ce9e to your computer and use it in GitHub Desktop.
Save ashalva/646bd5e62d67fea98c55fa420b86ce9e to your computer and use it in GitHub Desktop.
Sending get request in swift 4
import Foundation
enum Result<T> {
case success(T)
case failure(Error)
}
class Service: ServiceProtocol {
func get(callback: @escaping ((Result<[MyObject]>) -> ())) {
let url = URL(string: Links.baseUrl)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (responseData, response, responseError) in
DispatchQueue.main.async {
if let error = responseError {
callback(.failure(error))
} else if let jsonData = responseData {
let decoder = JSONDecoder()
do {
let objects = try decoder.decode([MyObject].self, from: jsonData)
callback(.success(objects))
} catch {
callback(.failure(error))
}
} else {
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Data was not retrieved from request"]) as Error
callback(.failure(error))
}
}
}
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment