1

I am trying to return the data from a asynchronous request's callback like below , but it's obviously not working . I want return the value inside the callback block to the main function , and other class can call this function by something like var sentiment = requestSentiment(text)

func requestSentiment(inputText : String!) -> NSDictionary?  {
        var searchString = inputText.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
        var escaspedSearchString = searchString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        var url = "\(baseURL)/sentiment?text=\(escaspedSearchString)"
        self.request.URL = NSURL(string: url)
        println(url)
        NSURLConnection.sendAsynchronousRequest(self.request, queue :NSOperationQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
            var error:AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult:NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error ) as? NSDictionary
            if (jsonResult != nil ){
                return jsonResult
            } else {
                NSLog("No data return")
                return nil
            }
        }
    }

I am appreciate anyone could help me with that , thanks !

Yank
  • 718
  • 6
  • 17
  • possible duplicate of [Return object for a method inside completion block](http://stackoverflow.com/questions/27953739/return-object-for-a-method-inside-completion-block) – Antonio Jan 24 '15 at 15:55

1 Answers1

1

What you are trying to do is inherently not possible because the request is asynchronous. Furthermore, you probably do not want to block the main thread waiting for a synchronous call to complete.

You need to change your design such that the caller passes a delegate object to your function. Then, the completion handler for sendAsynchronousRequest can invoke the delegate's method.

fred02138
  • 3,323
  • 1
  • 14
  • 17