1

cI'm trying to, with Swift 2 and Alamofire, make a request to an API, and then store the data so that I can use it in another function.

For example, this is my code below, and I'm trying to figure out how to assign it to a variable so that I can use it later in the file. I've tried Google'ing and trying a bunch of options and I haven't got anywhere in the past 3 hours.

func getToken() {
    Alamofire.request(.GET, "https://somesite.com/ping").responseJSON { response in
        print(response)
    }
}

So as we can see, we have the response, but could we assign the contents of it to a variable so we can use it in a function such as pryResponse?

func pryResponse() {
    print(response)
}

Something similar to that, but an actual variable.

Craytor
  • 117
  • 11

1 Answers1

-1

Try this.. The syntax changed a bit with the latest release.

Alamofire.request(.GET, "https://livewx.tv/ping").responseJSON(){
                (_, json, result) in
                switch result {

                case .Success:
                    let json = result.value!
                    let stuff = json["results"] as! [[String: AnyObject]]
                    //stuff now holds a dictionary with the json
                case .Failure(_,  _):
                    //Error
                }
            }
JDM
  • 883
  • 1
  • 8
  • 20
  • Thanks! I've tried this but there's some issues. I'm fairly new so I'm not the best at describing this yet, but here are the errors: http://d.pr/i/tse3 – Craytor Oct 16 '15 at 01:55
  • It looks like it's complaining about no code being present in the error case, add a print statement or anything else and see if it goes away. Of course you should handle the error , but it looks like as long as you have code there it'll stop complaining – JDM Oct 16 '15 at 02:05
  • Yeah, adding a print statement under .Failure fixed the small error, this one is still there though: http://d.pr/i/sFkj. – Craytor Oct 16 '15 at 02:17
  • Are you sure you're on the latest Alamo fire release? – JDM Oct 16 '15 at 02:53
  • 1
    I'm on ~>3.0 (I'm pretty sure it's the latest) – Craytor Oct 16 '15 at 03:24
  • 2
    This answer is valid for `Alamofire 2.0` – iRiziya Oct 16 '15 at 04:57
  • @irealme so I would have to downgrade? If so there has to be a way to get this to work with the latest release. – Craytor Oct 16 '15 at 13:43
  • @Craytor no you can also do the same with 3.0 too. See this http://stackoverflow.com/a/33130575/3734028 – iRiziya Oct 16 '15 at 13:51
  • @IRealMe Right, I've seen that one yesterday. Can I still do the same setup if I'm using it directly in a ViewController? Or does it have to be in a class? – Craytor Oct 16 '15 at 14:02
  • @Craytor you can do it directly too I guess – iRiziya Oct 16 '15 at 14:19
  • @Irealme Okay thanks for the response. I'll try it here tonight and get back to you about how it goes. – Craytor Oct 16 '15 at 20:30