Created
July 25, 2018 16:10
-
-
Save andru255/6c01f3e879eb7fc706f1cc2684d7c893 to your computer and use it in GitHub Desktop.
Función para realizar una petición al servicio de swapi
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
// 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