I want to make a generic HTTP request function. The code I saw does not return data to the caller. Instead it prints out the error code or the parsed JSON object within the function. In my case I would like to return (data, response, error) to the caller.
func performHTTPRequest(urlString: String) -> (Data, URLResponse, Error) {
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) {(data, response, error) in
// some logic
}
task.resume()
}
}
The problem is the three variables (data, response, error) are not available outside the closure. If I assign them to global variables within the closure, compiler complains the global variables are not in scope.
Also, where would I put the return (data, response, error) statement? Before or after task.resume()? Thanks