0

I have a function that is supposed to get json data and return it. This is the function below:

func httpjson(){
    let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) { (data, response, error) -> Void in
        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode
        if (statusCode == 200) {
            print("All OK!")
            do{
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
                return json
            }catch {
                print("Error with Json: \(error)")
            }
        }
    }
    task.resume()
}

The code returns the error Unexpected non-void return value in void function

After reading a little about this issue, I read that this can be fixed by changing func httpjson(){ to func httpjson()-> String{ but it still returns the same error.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
Matt
  • 1,087
  • 1
  • 12
  • 28

1 Answers1

0

The problem seems to be with your closure that's defined as (data, response, error) -> Void, not with the httpjson method.

Since your data task is asynchronous, httpjson has already returned by the time the JSON parsing finishes. It doesn't need to be defined as returning anything because there's nothing to return yet.

You need to do something with json (notification, callback, completion block, ...) to let the rest of your app know when it's ready to use.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57