I want to make a method with URL parameter that returns the response of calling that URL. How can I return the data obtained inside a completion block for a method?
class func MakeGetRequest(urlString: String) -> (data: NSData, error: NSError)
{
let url = NSURL(string: urlString)
var dataResponse: NSData
var err: NSError
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
//How can I return the data obtained here....
})
task.resume()
}
If you want the
MakeGetRequest
method to return data obtained viadataTaskWithURL
, you can't. That method performs an asynchronous call, which is most likely completed after theMakeGetRequest
has already returned - but more generally it cannot be know in a deterministic way.Usually asynchronous operations are handled via closures - rather than your method returning the data, you pass a closure to it, accepting the parameters which are returned in your version of the code - from the closure invoked at completion of
dataTaskWithURL
, you call that completion handler closure, providing the proper parameters:Swift 5 update: