Skip to content

Instantly share code, notes, and snippets.

@andru255
Created July 25, 2018 16:10
Show Gist options
  • Save andru255/6c01f3e879eb7fc706f1cc2684d7c893 to your computer and use it in GitHub Desktop.
Save andru255/6c01f3e879eb7fc706f1cc2684d7c893 to your computer and use it in GitHub Desktop.
Función para realizar una petición al servicio de swapi
// Función original
func getRemoteInfo(success: @escaping([String: Any]) -> Void, fail: @escaping(Error) -> Void ) {
let url = URL(string: "http://swapi.co/api/people/1/")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let sessionConf = URLSessionConfiguration.default
let urlSession = URLSession(
configuration: sessionConf,
delegate: nil,
delegateQueue: nil
)
let dataTask = urlSession.dataTask(
with: request as URLRequest,
completionHandler: {(data: Data?, response: URLResponse?, error) in
guard let data = data, error == nil else {
print("Error: \(error!.localizedDescription)")
fail(error!.localizedDescription as! Error)
return
}
if let httpStatus = response as? HTTPURLResponse {
if httpStatus.statusCode == 200 {
guard let json = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any] else {
print("Not containing JSON")
return
}
success(json)
}
}
})
dataTask.resume()
}
getRemoteInfo(success: { data in
print("name: ", data["name"]!) // Retornará el valor de la llave "name" que es "Luke Skywalker"
}, fail: {
print("fail: ", error) // Retornará un error del servicio
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment