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
CodePudding user response:
task.resume() will execute the URLSession request after you call it. The order of task.resume() is not important. When you resume it, the task will be executed and the completion will be called.
let task = session.dataTask(with: url) {(data, response, error) in
//This is a completion that will be executed after you call task.resume()
}
If you want to return all parameters to caller, you can do something like
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) {(data, response, error) in
return (data, response, error)
}
task.resume()
Also here is an example how you can return multiple parameters at the same time: Return multiple values from a function in swift
CodePudding user response:
The short answer is, you can't. You can us the new async/await syntax in Swift 5.5 to simulate a synchronous network call. (I haven't had a chance to use async/await in my own projects yet, so I'd have to look that up in order to guide you.)
Without async/await, you will need to refactor your function to take a completion handler. You'd then call the completion handler with the results once the data task completes.
This question comes up all the time on SO. You should be able to find dozens of examples of writing a completion handler-based function for async networking.
