0

I am trying to learn how to connect my app to a REST database. I am connecting to a dummy database called JSONPlaceholder.com and have successfully retrieved data. I now want to convert that NSDictionary into a custom object. Here is the GET method.

func apiGet () -> NSDictionary? {
var returnedNSDict: NSDictionary?
let postEndpoint = "http://jsonplaceholder.typicode.com/posts/1"
guard let url = NSURL(string: postEndpoint) else {
    print("Error: cannot create URL")
    return returnedNSDict
}

let urlRequest = NSMutableURLRequest(URL: url)
urlRequest.HTTPMethod = "GET"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
  let session = NSURLSession(configuration: config)
  let task = session.dataTaskWithRequest(urlRequest, completionHandler:
    { (data: NSData?, response: NSURLResponse?, error: NSError?) in
        guard let returnedData = data else {
            print("Error: did not receive data")
            return
        }
        guard error == nil else {
            print ("Error calling get is: \(error)")
            return
        }

        let post: NSDictionary
        do {
            post = try NSJSONSerialization.JSONObjectWithData(returnedData,
                options: []) as! NSDictionary
        } catch  {
            print("error calling GET")
            return
        }
        returnedNSDict = post
})

task.resume()
return returnedNSDict

}

You'll noticed that the method is supposed to return a NSDictionary. My thinking here is if I can get this method to return a NSDictionary then I can call it from elsewhere and convert that dictionary into a custom object.

My problem is the completion seems to run AFTER the return call of the method, so keeps returning NIL. How can I assign the NSDictionary I am accessing in the completion handler to a value that I can then return when this method is called?

Thanks in advance.

thecloud_of_unknowing
  • 1,103
  • 14
  • 23
  • This question has been asked and answered about 10,000,000 times on SO. Please search instead of wasting bandwidth. – matt Mar 28 '16 at 15:40
  • Thanks @matt, I did search - for about 20 minutes - but because I didn't understand the problem, wasn't using the correct search terms. Your answer is much appreciated. Your book also helped a great deal. Thanks. – thecloud_of_unknowing Apr 05 '16 at 17:06
  • The book needs a more explicit section on this, though. Clearly I'm not helping people grasp what asynchronous means... – matt Apr 05 '16 at 17:08
  • I don't think that's the problem. What asynchronous means is easy to understand. The hard part is understanding how a function declared in one context can be passed into another context (as an argument in a function), grab a value in that new context, and then send that value back to the original context in which the function was first declared. The point of confusion 4 me was: I failed to grasp that the point at which the captured value becomes accessible is in the body of the function that is passed. Instinctively I kept looking for it in the main func since that is the primary func called. – thecloud_of_unknowing Apr 05 '16 at 17:26
  • OK, but people still seem to think you can pass back a value received in a completion handler just by returning it somehow. I need to be more insistent that it doesn't work that way. :) – matt Apr 05 '16 at 17:30

0 Answers0