da1lbi3 da1lbi3 - 1 year ago 46
Swift Question

Is it possible to return result set from POST call

I have this code:

private func data_request(url : String)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

let url:NSURL = NSURL(string: self.self.newUrl.createUrl(url))!
let session = NSURLSession.sharedSession()

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

let paramString = "data=Hello"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

let task = session.dataTaskWithRequest(request) {
let data, let response, let error) in

guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {

let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)



I call it like this:
var result = data_request("localhost/test");

That is working fine, but is it possible to return the results from the request function? My plan is to put the result in the result variable.


You should use closures to get the data since the NSURLSession API is asynchronous, meaning that you don't know when the data will arrive. It may be instantly or in 10 seconds, you never know. You will return from the function immediately, but you'll get the value from the closure.

private func data_request(url : String, completion: (String) -> ()) {
    let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    // Now call completion to pass the value

And when you need to call the function you will use:

data_request("http://someapi.com/api") {
    dataString in
    print(dataString) // This is the string you passed to the completion