在Swift中处理Alamofire的JSON响应 [英] Handle JSON Response with Alamofire in Swift

查看:1399
本文介绍了在Swift中处理Alamofire的JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉我的英文不好:)

我在Swift中针对iOS应用程序解析Alamofire上的JSON响应时遇到问题。我写了一个函数来返回一个JSON响应字符串。我使用 Alamofire 处理的请求和响应处理以及我使用 SwiftyJSON 。在开始时,我声明一个名为 jsonString 的var,其值为 test 。然后我向REST服务发出请求,并通过单击按钮获取JSON响应。我希望使用函数 ping(url:String)返回此响应。最后,我打印返回的响应作为测试。但是,首次点击按钮时, ping 的返回值为测试,而不是响应的JSON字符串。在第二次单击按钮时,我得到正确的返回值。为什么我有这个问题。 Alamofire请求是异步操作吗?我想等待回应。如何解决问题以便在第一次点击时获得正确的价值,而不是测试作为价值?

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?

这是我的代码:

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


推荐答案

在第一次点击,代码

return self.jsonString

将在

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

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

你将在第一次从self.jsonString获得nil,你第二次点击将获得第一次点击的请求数据。

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

如果您使用SwiftyJSON和Alamofire,您可以尝试 Alamofire-SwiftyJSON

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

这篇关于在Swift中处理Alamofire的JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆