Last active
July 26, 2018 06:07
-
-
Save ashalva/646bd5e62d67fea98c55fa420b86ce9e to your computer and use it in GitHub Desktop.
Sending get request in swift 4
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 | |
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