Trying to access answers globally

I am using Alamofire and when I get a response, I try to set it as a variable that I can access anywhere. That's what i'm going to

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 I get nil

.... Any ideas? I know the request is good because I can see the response inside the scope when I don't assign it to a variable.

+3


source to share


2 answers


Almofire.request

- an asynchronous function. You name it and he will return immediately; before it actually fulfills the request. Thus, it println(data)

is called before anything ever sets data

to something other than nil

. When the request is indeed complete, Alamofire will trigger the closure you pass to responseJSON

, in that closure you will 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 let's say that I want to turn this data into a table. Would I just put all the table code in a closure?

You can put all of this code in a closure, but this is likely to be pretty confusing. The best way to handle this is to implement the same pattern that it uses Alamofire.request

. Basically, make your request, its own function will accept the closure as a parameter. Then, in the closure, you go to responseJSON

, call the closure passed to your function by passing it data

. Then make a separate "turn this data into a table" function and call it with data

from your closure. Something like that:

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 probably want to convert data

to something other than AnyObject?

, at some point in there.

+6


source


This is because when you do let data: AnyObject? = JSON

, you created a new local variable data

in the closure.

Instead, you should do this:



var data: NSData?
Alamofire.request(.POST, "http://localhost/api/notifications", parameters: parameters)
    .responseJSON { (request, response, JSON, error) in
           data = JSON 
    }
println(data)

      

-1


source







All Articles