在Swift中处理Alamofire的JSON响应

编程入门 行业动态 更新时间:2024-10-26 15:25:54
本文介绍了在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("test") 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响应

本文发布于:2023-11-26 01:54:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632177.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   Alamofire   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!