I'm using Alamofire and when I get the response I'm trying to set it as a variable that I can access anywhere. Here's what I got going
var data: NSData?
Alamofire.request(.POST, "http://localhost/api/notifications", parameters: parameters)
.responseJSON { (request, response, JSON, error) in
let data: AnyObject? = JSON
}
println(data)
And when I run that I get nil.... Any ideas? I know that the request is good because I can see the response inside the scope when I don't assign it to a variable.
Almofire.request is an asynchronous function. You call it and it will return immediately; before it actually does the request. So, println(data) gets called before anything ever sets data to something other than nil. When the request is actually complete, Alamofire will call the closure you pass to responseJSON, in that closure is where you'll want to actually use data (print it or whatever):
Alamofire.request(.POST, "http://localhost/api/notifications", parameters: parameters)
.responseJSON { (request, response, JSON, error) in
let data: AnyObject? = JSON
// do something useful with data
println(data)
}
Question from comments:
But then lets say I want to turn that data into a table. Would I just put all the table code inside the closure?
You could put all that code inside the closure, but that will probably get messy pretty quickly. A better way to handle that is to implement the same sort of pattern that Alamofire.request is using. Basically, make your request its own function will takes a closure as a parameter. Then, in the closure you pass to responseJSON, call the closure passed to your function passing it data. Then, make a separate function to "turn that data into a table" and call it with data from your closure. Something like this:
func callSomeAPI(resultHandler: (data: AnyObject?) -> ()) -> () {
Alamofire.request(.POST, "http://localhost/api/notifications", parameters: parameters)
.responseJSON { (request, response, JSON, error) in
let data: AnyObject? = JSON
resultHandler(data)
}
}
func makeTable(data: AnyObject?) -> () {
// make your table
}
callSomeAPI() { data in
makeTable(data)
}
Note: You'll probably want to convert data to something other than AnyObject? at some point in there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With