14

I am doing the HTTP request and getting response in my func. It return the value of response. I am doing it this way:

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
        stringResponse = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
        if stringResponse == "0" {
            return false
        } else if stringResponse == "1" {
            return true
        } else {
            return false
        }
    }

But on all returns I have error Unexpected non-void return value in void function How to fix this?

Nikita Zernov
  • 5,465
  • 6
  • 39
  • 70

2 Answers2

18

Do this if you want the value after you get response.

func getResponse(completionHandler : ((isResponse : Bool) -> Void)) {

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
        stringResponse = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
        if stringResponse == "0" {
           completionHandler(isResponse : false)
        } else if stringResponse == "1" {
           completionHandler(isResponse : true)
        } else {
           completionHandler(isResponse : false)
        }
    }
}

Now you call it as below from where ever you are calling.

classObject.getResponse {(isResponse) -> Void in 

//Do your stuff with isResponse variable.
}
Amit89
  • 3,000
  • 1
  • 19
  • 27
0

The last parameter of sendAsynchronousRequest is a completion handler with type (NSURLResponse!, NSData!, NSError!) -> Void. Note it doesn't have any return type, so don't return anything.

The completion handler is called by the connection framework, it doesn't need any return type.

It's pretty obscure what you are trying to achieve by that returns but you can't do it this way.

Sulthan
  • 128,090
  • 22
  • 218
  • 270