在 Swift 3 中将提取的 JSON 解析为字典 [英] Parsing fetched JSON to dictionary in Swift 3

查看:36
本文介绍了在 Swift 3 中将提取的 JSON 解析为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中的某个时刻,用户提供了一个电影名称.控制器将从 OMDB 获取有关电影的更多信息并存储它.我在将 JSON 从 url 转换为字典时遇到了问题.这是我的代码:

At some point in my app the user supplies a movie name. The controller will get more info about the movie from OMDB and store it. I run into problems getting converting the JSON from the url into a dictionary. Here's my code:

@IBAction func addMovieButtonPressed(_ sender: Any) {
    // get title from the text field and prepare it for insertion into the url
    let movieTitle = movieTitleField.text!.replacingOccurrences(of: " ", with: "+")
    // get data for the movie the user named
    let movieData = getMovieData(movieTitle: movieTitle)
    // debug print statement
    print(movieData)
    // reset text field for possible new entry
    movieTitleField.text = ""
}

// function that retrieves the info about the movie and converts it to a dictionary
private func getMovieData(movieTitle: String) -> [String: Any] {

    // declare a dictionary for the parsed JSON to go in
    var movieData = [String: Any]()

    // prepare the url in proper type
    let url = URL(string: "http://www.omdbapi.com/?t=\(movieTitle)")

    // get the JSON from OMDB, parse it and store it into movieData
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else { return }
        do {
            movieData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
        } catch let error as NSError {
            print(error)
        }
    }).resume()

    // return the data
    return movieData
}

我尝试了在 Stackoverflow 上找到的 URLSession 部分的许多变体,我知道数据已成功获取:

I have tried many variations of the URLSession part that I found on Stackoverflow and I know that the data is successfully fetched:

但是我不知道如何正确地获取它并将其转换为字典,然后我可以在我的应用程序的其余部分中使用它.IBAction 函数中的打印语句总是返回一个空字典.

However I don't know how to properly get at it and turn it into a dictionary I can then use in the rest of my app. The print statement in the IBAction function always returns an empty dictionary.

我做错了什么?

推荐答案

查看完成块和异步函数.您的 getMovieData 在调用数据任务的完成处理程序之前返回.

Look into completion blocks and asynchronous functions. Your getMovieData is returning before the datatask's completion handler is called.

您的函数将调用传入的完成块而不是返回,并应更改为:

Your function, instead of returning, will call the completion block passed in and should change to:

private func getMovieData(movieTitle: String, completion: @escaping ([String:Any]) -> Void) {

    // declare a dictionary for the parsed JSON to go in
    var movieData = [String: Any]()

    // prepare the url in proper type
    let url = URL(string: "http://www.omdbapi.com/?t=\(movieTitle)")

    // get the JSON from OMDB, parse it and store it into movieData
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else { return }
        do {
            movieData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
            completion(movieData)
        } catch let error as NSError {
            print(error)
        }
    }).resume()
}

这篇关于在 Swift 3 中将提取的 JSON 解析为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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