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 !

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

hi @fred thanks ! can you be more specific about how to do this ?
thanks problem has been solved by implementing completion handler , thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.