Last active
May 27, 2019 05:22
-
-
Save MaatheusGois/653218fb01e8bf97694b9be907b9e583 to your computer and use it in GitHub Desktop.
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
//Não esqueca de importar o Foundation | |
func getRequest(url: String, | |
completion: @escaping ([String: Any]?, Error?) -> Void){ | |
//URL válida | |
guard let URL = URL(string: url) else { | |
completion(nil, nil) | |
return | |
} | |
//Cria a representacão da requisição | |
let request = NSMutableURLRequest(url: URL) | |
//Atribui à requisiçāo o método GET | |
request.httpMethod = "GET" | |
//Cria a tarefa de requisição | |
let task = URLSession.shared.dataTask(with: request as URLRequest) { | |
(data, response, error) in | |
do { | |
if let data = data { | |
//A resposta chegou | |
let response = try JSONSerialization.jsonObject(with: data, options: []) | |
completion(response as? [String : Any], nil) | |
} | |
else { | |
//Não houve resposta | |
completion(nil, nil) | |
} | |
} catch let error as NSError { | |
// Houve um erro na comunicao com o servidor | |
completion(nil, error) | |
} | |
} | |
//Aciona a tarefa | |
task.resume() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment