Ok so first of all, I've read several other post on the subject and I know that what Im going to describe could be a synchronous call but what I really need is to get the data and work with it, so if I should look in some other direction let me know:
I have to make calls to an api to retrieve json objects and use them to populate a table view. my problem is that I can't manage to pass / return the data to work with it:
in the controller:
callProjectTypes()
var testjson = JSON(data:test)
println("should print some data")
println(testjson[0])
the call functions:
func callProjectTypes() -> (NSData) {
var data = NSData()
serverCall("http://url/to/project/types") {
responseData, error in
if responseString == nil {
println("Error during post: \(error)")
return
}
// use responseData here
data = responseData
}
return data
}
func serverCall(url: String, completionHandler: (responseData: NSData!, error: NSError!) -> ()) {
var URL: NSURL = NSURL(string: url)!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "GET";
var creds = encodeCredentials()
request.addValue("\(creds)", forHTTPHeaderField: "Authorization")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){
response, data, error in
var output: NSData!
if data != nil {
output = data
}
completionHandler(responseString: output, error: error)
}
}
println(testjson[0])
always return "nill
" so I assume the "return data
" from my callProjectTypes
function is coming back before the data arrived.
What should I do to make this work?