ios - Swift中JSON解析返回数据

标签 ios json swift parsing

我有一个 Swift 代码,用于从 Web 检索和解析 JSON 数据。除了我现在面临的一个问题外,一切似乎都很好。我试着解决了一段时间,在线检查了所有资源。

我已经创建了全局字典“dicOfNeighbours”,它希望通过调用“func startConnection”作为解析结果返回到其他类。

dicOfNeighbours 存储已解析的数据,直到它超出以下的右括号: “让任务 = session.dataTaskWithRequest(urlRequest) { ... }” 在它只存储nil 之后。返回结果也为零。

我尝试使用 inout 通过引用传递“dicOfNeighbours”变量,但它仍然返回 nil 结果。

可能有一些我错过的解决方案。 我将不胜感激任何帮助和建议。

谢谢!

    var dicOfNeighbours = Dictionary<String, [Int]>()

        func startConnection() -> Dictionary<String, [Int]>{
                let requestURL: NSURL = NSURL(string: "http://www....data.json")!
                let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
                let session = NSURLSession.sharedSession()
                let task = session.dataTaskWithRequest(urlRequest) {
                    (data, response, error) -> Void in

                    let httpResponse = response as! NSHTTPURLResponse
                    let statusCode = httpResponse.statusCode

                    if (statusCode == 200) {

                        do{

                            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                            if let neighbours = json["neighbours"] as? [String: Array<Int>] {
                                    var i = 0
                                    for (index, value) in neighbours {
                                        self.dicOfNeighbours[index] = value

                                }

                            }

                        }catch {
                            print("Error with Json: \(error)")

                        }               
                    }
                }
                task.resume()
return self.dicOfNeighbours
            }

最佳答案

您正在使用 return 而不是使用回调。网络连接完成后,您正在进行解析;异步。

要同步它,您需要使用信号量,但在主线程上非常不鼓励这样做。

相反,当你的完成 block 被执行时,对结果做适当的事情。将数据任务视为“做事,完成后回来找我”。

关于ios - Swift中JSON解析返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35059910/

相关文章:

ios - UIButton 图像位置取决于 titleLabel 的框架

ios - 不断打开 OS X 和 iOS 之间的 BLE 连接

ios - crash - 重击 @escaping @callee_guaranteed (@unowned CMTime)

屏幕锁定时不调用ios NotificationService Extension

c++ - 使用 lib Rapidjson 将混合 JSON 数字数组转换为 int、uint、float

javascript - 使用 django 在 JS 中获取和使用 python 嵌套列表

ios - Firebase 查询无法正常工作

SwiftUI:ListItem手势

macos - Swift: undefined symbol :iTunesApplication

json - 使用 AngularJS 解析带有数组的 JSON 文件