0

My function is like this:

class function functionName(..args) ->NSData {

  var data : NSData?

  object1.operation(arg1,arg2, onComplete:{

    (error:NSError) -> Void in 

     /*My Code For Downloading data goes Goes Here*/
     data = downloadedData
   }) 

   return data

}

So, what happening is before the execution of object1.operation , my code is getting to return data statement.

How can I prevent further execution of my function until the object1.operation method gets completed? I've tried dispatch_semaphone , dispatch_group, dispatch_async, dispatch_sync, etc .. none of them helped.

A.L
  • 10,259
  • 10
  • 67
  • 98
SiltyDoubloon
  • 147
  • 2
  • 3
  • 11
  • 4
    The whole point of a block is to do things async, your function is setup in a sync way. What you should do is rather provide the function with its own callback/closure/block that can be called with the data once the block has been completed. @jcesarmobile returning inside the block, returns to the block not the function. – sbarow Jun 24 '15 at 11:51
  • @jcesarmobile I won't work the method is synchronous. – Otávio Jun 24 '15 at 11:52
  • Alamofire can help you. Look at this: http://stackoverflow.com/questions/28634995/chain-multiple-alamofire-requests – Klevison Jun 24 '15 at 11:53
  • @jcesarmobile This doesn't make sense for several reasons: the block is declared to return nothing (void), the method will probably be called asynchronous, the given function will probably return immediately (before the block is executed). – Eiko Jun 24 '15 at 11:56

1 Answers1

0

you can do something like this:

func url(absoluteURL: String, method: String, completion: ((nsData: NSData?) -> Void)!) {

        _rawURL  = NSURL(string: absoluteURL)
        _request = NSMutableURLRequest(URL: _rawURL)

        _request.HTTPMethod = method

        //Async Task
        var task: NSURLSessionDataTask = _session.dataTaskWithRequest(_request) {
            (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in

            if (error == nil) {
                var httpResponse: NSHTTPURLResponse = response as! NSHTTPURLResponse

                if (httpResponse.statusCode == 200) {

                    dispatch_async(dispatch_get_main_queue()) {
                        completion(nsData: data);
                    }
                }
            }

        }

        task.resume()
    }

This is just a sample code but you can see here how to use completion block on function signature....

Himanshu gupta
  • 650
  • 5
  • 10