-2

I'm trying to extract JSON from request so I can use it in my code. But nil is returned(Actual string in console is And here is JSON nil)

class ViewController: UIViewController {

    var myVar: AnyObject?

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, "http://httpbin.org/get")
            .responseJSON { _, _, JSON, _ in
            self.myVar = JSON
        }
        println("And here is JSON \(self.myVar)")
    }
}

What have I to do to solve the problem ?

Lucas Huang
  • 3,998
  • 3
  • 20
  • 29
Alexey K
  • 6,537
  • 18
  • 60
  • 118
  • From https://github.com/Alamofire/Alamofire: *"Networking in Alamofire is done **asynchronously**. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are very good reasons for doing it this way. Rather than blocking execution to wait for a response from the server, a callback is specified to handle the response once it's received. **The result of a request is only available inside the scope of a response handler.** Any execution contingent on the response or data received from the server must be done within a handler."* – Martin R Jul 16 '15 at 17:33

1 Answers1

0

First of all, you need to understand whether the call is asynchronous. If so, there is no result when you execute println. You can put your println inside the result block like this:

Alamofire.request(.GET, "http://httpbin.org/get")
.responseJSON { _, _, JSON, _ in
    self.myVar = JSON
    println("And here is JSON \(self.myVar)")
}
Lucas Huang
  • 3,998
  • 3
  • 20
  • 29
  • sorry, Im new to iOS and programming at all, so im not familar with some concepts. – Alexey K Jul 16 '15 at 17:50
  • You need to look it up what's async and non-async networking call. @AlexeyK – Lucas Huang Jul 16 '15 at 17:51
  • according to your example it prints ok, but i cant store JSON result in variable. IS there any way to do this if printing is possible ? – Alexey K Jul 16 '15 at 18:12
  • What do you mean by that? What kind of data type is that? `[AnyObject:AnyObject]` or `[AnyObject]`? – Lucas Huang Jul 16 '15 at 18:16
  • made this work by trying.I have one question - i dont have anywhere variable MyQuests inside function or closure but it prints ok. Can you please describe why is it happens so ? func getQuests(completionHandler: (NSDictionary) -> Void) { Alamofire.request(.GET, "http://httpbin.org/get").responseJSON { _, _, json, _ in completionHandler(json as! NSDictionary) } } var myQuests: NSDictionary? getQuests() { quests in myQuests = quests println("My Quests: \(myQuests)") } – Alexey K Jul 16 '15 at 18:46
  • U need to tell compiler what data type it's. Otherwise, it will think that it's AnyObject type and it doesn't know how to match it. – Lucas Huang Jul 16 '15 at 19:51