Handle JSON Response with Alamofire in Swift

13,109

Solution 1

In the first click, the code

return self.jsonString

will run before

.response {
        (request, response, data, error) -> Void in

        let json = JSONValue(data as? NSData)
        self.jsonString = json.rawJSONString
}

you will get nil form the self.jsonString in the first time, you second click will get the first click's request data.

If you use SwiftyJSON and Alamofire you can try Alamofire-SwiftyJSON

Solution 2

You could also try running

dispatch_sync(dispatch_get_main_queue()) {
  // insert code you need done the first time around - it will wait
}
Share:
13,109
GRme
Author by

GRme

Updated on June 04, 2022

Comments

  • GRme
    GRme almost 2 years

    sorry for my bad english :)

    I have a problem to parse JSON response over Alamofire in Swift for an iOS app. I wrote a function to return a string of JSON response. The request and response handling I do with Alamofire and the JSON handling I do with SwiftyJSON. At the begin I declare a var called jsonString with the value test. Then I do a request to an REST Service and get a JSON response by clicking a button. This response I want to return with the function ping(url:String). At the end I print the returned response as a test. But on the first click on the button the return value from ping is test and not the JSON string of the response. On the second click on the button I get the right return value. Why I have this problem. Is the Alamofire request an asynchronous operation? I want to wait for the response. How can I solve the problem to get the right value on first click and not test as value?

    Here is my code:

    var jsonString:String = "test"
    
    func ping(url:String) -> String {
    
        Alamofire.request(.GET, url)
            .response {
                (request, response, data, error) -> Void in
    
                let json = JSONValue(data as? NSData)
                self.jsonString = json.rawJSONString
        }
    
        return self.jsonString
    }
    
    @IBAction func checkOnlineStatus(sender: UIButton) {
    
        let response:String = ping("http://test.com")
    
        println(response)}