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.