Search code examples
iosiphonejsonswiftalamofire

Handle JSON Response with Alamofire in Swift


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)}

Solution

  • 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